public LineMatch(string token, string text, ParsedLine parsedLine, Lexer lexer) { Token = token; Text = text; ParsedLine = parsedLine; Lexer = lexer; }
private void ExtractGlobalInfo(ParsedLine line) { if (line.GetLineType() == 'G') { globalInfo += line.GetContent(); } }
protected override void OnStoryUpdate(ParsedLine parse, bool visited) { Parse dialog = parse.Find(HalfwayHomeStoryReader.dialogLabel); if (parse.HasTag("skip")) { Space.DispatchEvent(Events.NextLine); } // 1. Monologue bool isMonologue = (dialog == null); if (isMonologue) { Space.DispatchEvent(Events.Description, new DescriptionEvent(parse.line, "")); return; } // 2. Dialog: Update the current speaker Parse speaker = parse.Find(HalfwayHomeStoryReader.speakerLabel); if (speaker != null) { currentSpeaker = speaker.value; } Space.DispatchEvent(Events.Description, new DescriptionEvent(dialog.value, currentSpeaker)); }
public void ToggleSetting(ulong address, AddressInfo info) { // Set AddressInfo at a particular line. Nothing happens if the line is in a range but isn't an instruction(e.g mid way through one), // but one will be created if it is out of any existing range. // Find the address range the address lies in AddressMap.BinarySearchResult index = Map.Search(address); // If it not present, disassemble it and toggle it. I would imagine the only time for this to happen would be if instructions were // unpacked onto the stack then executed there. A rare case but one worth accounting for. if ((index.Info | AddressMap.BinarySearchResult.ResultInfo.PRESENT) != index.Info) { DisassembleStep(address); ToggleSetting(address, info); } else { // Iterate through each line in the address range until the desired is found, then OR its $Info with $info. ListeningList <ParsedLine> Lines = ParsedLines[Map[index.Index]]; for (int i = 0; i < Lines.Count; i++) { if (Lines[i].Address == address) { Lines[i] = new ParsedLine(Lines[i], info); } } } }
/// <summary> /// Loads a scenario from a text given in our domain-specific language created for this purpose and returns it /// as a list of commands. /// </summary> /// <param name="data">Contents of the scenario file.</param> /// <returns></returns> public static List <ScenarioCommand> LoadFromText(string data) { List <ScenarioCommand> commands = new List <ScenarioCommand>(); string[] lines = data.Split(new[] { '\n' }, StringSplitOptions.RemoveEmptyEntries); for (int i = 0; i < lines.Length; i++) { string line = lines[i]; if (line.Trim() == "") { continue; } ParsedLine parsedLine = ParsedLine.Parse(line); if (parsedLine.Command == "menu") { ParsedLine option1 = ParsedLine.Parse(lines[i + 1]); ParsedLine option1Then = ParsedLine.Parse(lines[i + 2]); ParsedLine option2 = ParsedLine.Parse(lines[i + 3]); ParsedLine option2Then = ParsedLine.Parse(lines[i + 4]); i += 4; commands.Add(new MenuCommand(option1, option1Then, option2, option2Then)); } else { commands.AddRange(ParseCommand(parsedLine)); } } commands.Add(new EndScenarioCommand()); return(commands); }
public IObservable <string> Evaluate(ParsedLine line) { if (!line.IsCommand || line.Command.ToLower() != "reminder") { return(null); } string help = "!reminder [time] [message]"; // Verify we have enough arguments if (line.Args.Length < 2) { return(Observable.Return(help)); } DateTimeOffset time; // Parse the arguments if (!DateTimeOffset.TryParse(line.Args[0], out time)) { return(Observable.Return(help)); } // We want anything entered after the time to be included in the reminder string message = line.Args.Skip(1).Aggregate(String.Empty, (s, s1) => s + (s.Length == 0 ? "" : " ") + s1); // Create an sequence that fires off single value at a specified time // and transform that value into the reminder message IObservable <string> seq = Observable.Timer(time).Select(l => message); // Add a start message return(Observable.Return(String.Format("Will do - I'll remind you at {0}.", time)) .Concat(seq)); }
/// <summary> /// Parsing the Line (No magic) /// </summary> /// <param name="line"></param> /// <returns></returns> private ParsedLine ParseLine(string line) { var parsedString = new ParsedLine(); var lineLength = line.Length; // read last three characters var lastThreeCharcters = line.Substring(lineLength - MinLiteralStringToken.Length); var builder = new StringBuilder(); // Must be Lightning talk if (!string.Equals(lastThreeCharcters, MinLiteralStringToken)) { parsedString.IsLightning = true; builder.Insert(0, lastThreeCharcters); } // It does not matter parse through till the start get clear picture var pos = MinLiteralStringToken.Length + 1; var currIndex = lineLength - pos; while (currIndex >= 0) { var currChar = line[lineLength - pos]; if (currChar == ' ') // break when you find space ;) { break; } builder.Insert(0, currChar); pos++; currIndex = lineLength - pos; } parsedString.Value = builder.ToString(); // Evil data check parsedString.Name = line.Substring(0, currIndex >= 0 ? currIndex : 0); return(parsedString);; }
// Helper method private SessionTalk MapParsedTalkToSessionTalk(ParsedLine parsedLine, int minutes) { return(new SessionTalk { Minutes = parsedLine.IsLightning ? LightningTalkMinutes : minutes, TalkName = parsedLine.Name, }); }
public IObservable <string> Evaluate(ParsedLine line) { if (!line.IsCommand || line.Command.ToLower() != "countdown") { return(null); } var options = new CountdownTimerOptions(); if (!Parser.Default.ParseArguments(line.Args, options)) { return(Return(options.GetUsage())); } try { int seconds = options.DurationSeconds; int interval = options.IntervalSeconds; var unitLabels = options.ParseUnitLabels(options.IntervalString); // Create an interval sequence that fires off a value every [interval] seconds IObservable <string> seq = Interval(TimeSpan.FromSeconds(interval)) // Run that seq until the total time has exceeded the [seconds] value .TakeWhile(l => ((l + 1) * interval) < seconds) // Project each element in the sequence to a human-readable time value .Select( l => String.Format("{0} remaining...", FormatRemaining(seconds - ((l + 1) * interval), unitLabels))); // If there are any other events configured, merge them into the sequence if (options.Events.Any()) { var events = options.Events.OrderBy(@event => @event.Target); var eventTimes = Interval(TimeSpan.FromSeconds(1)) .TakeWhile(l => l < seconds) .Where(l => events.Any(@event => @event.Target == l)) .Select(l => events.First(@event => @event.Target == l).Message); seq = seq.Merge(eventTimes); } // Add a start and end message return(Return(String.Format("{0} remaining...", FormatRemaining(seconds, options.ParseUnitLabels(options.DurationString)))) .Concat(seq) .Concat(Return(String.Join(" ", options.FinishedMessage)))); } catch (ArgumentException) { return(Return(options.GetUsage())); } }
private void AssertDataForTheFirstRecord(ParsedLine firstRecord) { Assert.IsTrue(firstRecord[TestData.FieldReservationNumber].Equals("04416365US2")); Assert.IsTrue(firstRecord[TestData.FieldCheckInDate].Equals("2015-01-23")); Assert.IsTrue(firstRecord[TestData.FieldCalcNetAmount].Equals("437.39")); Assert.IsTrue(firstRecord[TestData.FieldCustomerName].Equals("KAY KENG,LOW")); Assert.IsTrue(firstRecord[TestData.FieldRunDate].Equals("2015-01-28")); Assert.IsTrue(firstRecord[TestData.FieldCurrencyConvRate].Equals("0.762728")); Assert.IsTrue(firstRecord[TestData.FieldUsDollarAmountDue].Equals("220.26")); Assert.IsTrue(firstRecord[TestData.FieldDateOfBirth].Equals("1972-08-09")); }
public Parser(string igs) { lines = igs.Split('\n'); parsedLines = new ParsedLine[lines.Length]; for (var i = 0; i < lines.Length; i++) { if (lines[i].Length > 0) { parsedLines[i] = new ParsedLine(lines[i]); ExtractGlobalInfo(parsedLines[i]); } } }
public void NotSupportedException() { Assert.Throws <NotSupportedException>(() => new ParsedFile(_validPath + "Sample_file.txt").ToList <uint>()); Assert.Throws <NotSupportedException>(() => new ParsedFile(_validPath + "Sample_file.txt").ToList <DateTime>()); var line = new ParsedLine(new Queue <string>(new string[] { "1234" })); Assert.Throws <NotSupportedException>(() => line.NextElement <ulong>()); IParsedFile parsedFile = new ParsedFile(_validPath + "Sample_file.txt"); IParsedLine firstParsedLine = parsedFile.NextLine(); Assert.Throws <NotSupportedException>(() => firstParsedLine.NextElement <char>()); }
public void AccessClassFunction() { ParsedLine line = new ParsedLine("public: unsigned long long int testClass::testFunction() 0xFFFFFFFF"); ParsedClass theClass = new ParsedClass(line); ParsedFunction func = new ParsedFunction(line, theClass); bool decorators = func.accessLevel.HasValue && func.accessLevel.Value == FuncAccessLevel.PUBLIC && !func.isStatic && !func.isVirtual && !func.isConstructor && !func.isDestructor && !func.callingConvention.HasValue; if (!decorators) { Assert.Fail("Decorators failed to pass"); } bool returnType = func.returnType.isBaseType && func.returnType.baseType.Value == BuiltInCppTypes.UNSIGNED_LONG_LONG_INT && func.returnType.type == "unsigned long long int" && !func.returnType.isConst && !func.returnType.isPointer && !func.returnType.isConstPointer && !func.returnType.isReference; if (!returnType) { Assert.Fail("Return type failed to pass"); } Assert.IsTrue(func.parameters.Count == 0, "Param count failed to pass"); bool names = func.parentClass.name == "testClass" && func.name == "testFunction"; if (!names) { Assert.Fail("Names failed to pass"); } bool end = !func.isConst && func.address == 0xFFFFFFFF; if (!end) { Assert.Fail("End failed to pass"); } }
public void h_returns_help() { var scheduler = new TestScheduler(); var plugin = new CountdownTimer(scheduler); var pl = new ParsedLine("!countdown -h", "Bob"); IObservable <string> results = plugin.Evaluate(pl); ITestableObserver <string> obs = scheduler.Start(() => results); obs.Messages.First().Value.Value.Should().Contain("!countdown -d <duration> -i <interval> [options]"); }
private void AddNewLines(ListeningList <ParsedLine> lines) { // Format each struct in the input and set its index to where it is in the items of this control. This makes // life easier later. for (int i = 0; i < lines.Count; i++) { lines[i] = new ParsedLine(lines[i]) { Index = Items.Count }; FormatAndApply(lines[i]); } // Update the lines automatically later. lines.OnSet += (line, index) => FormatAndApply(line); lines.OnAdd += (line, index) => FormatAndApply(line); }
public override string EvaluateEx(ParsedLine line) { if (!line.IsCommand || line.Command.ToLower() != "countdown") { return(null); } string help = "!countdown [seconds] [interval]"; // Verify we have enough arguments if (line.Args.Length < 2) { return(help); } int seconds; int interval; // Parse the arguments if (!int.TryParse(line.Args[0], out seconds) || !int.TryParse(line.Args[1], out interval)) { return(help); } // Create an interval sequence that fires off a value every [interval] seconds IObservable <string> seq = Observable.Interval(TimeSpan.FromSeconds(interval)) // Run that seq until the total time has exceeded the [seconds] value .TakeWhile(l => ((l + 1) * interval) < seconds) // Project each element in the sequence to a human-readable time value .Select( l => String.Format("{0} seconds remaining...", seconds - ((l + 1) * interval))) .Concat(Observable.Return("Finished!")); seq.Subscribe((msg) => { this.SendMessage(msg, line.From, BotMessageType.groupchat); }); return(null); }
public void finish_help_formats_default() { var scheduler = new TestScheduler(); var plugin = new CountdownTimer(scheduler); var pl = new ParsedLine("!countdown", "Bob"); IObservable <string> results = plugin.Evaluate(pl); ITestableObserver <string> obs = scheduler.Start(() => results); obs.Messages.First().Value.Value.Contains("System.String[]") .Should().BeFalse("the formatting of the default value shouldn't be System.String[]"); obs.Messages.First().Value.Value.Contains("(Default: Finished!)") .Should().BeTrue(); }
public static ParsedLine Parse(string line) { var parsedLine = new ParsedLine { Line = line }; var obj = line.TrimEnd(); var lSpaceMatch = Regex.Match(obj, @"^[\s]+"); if (lSpaceMatch.Success) { parsedLine.Tab = lSpaceMatch.Length / 4; } else { parsedLine.Tab = 0; } foreach (var match in Regex.Matches(obj, @"\[(.+?)(\`.+?)?\]").Cast <Match>().Reverse()) { obj = obj.Remove(match.Index, match.Length).Insert(match.Index, match.Groups[1].Value); parsedLine.InnerLines.Insert(0, new string(' ', (parsedLine.Tab + 1) * 4) + match.Groups[1].Value + match.Groups[2].Value.Trim()); } obj = obj.Trim(); parsedLine.Predicate = ""; obj = obj.Replace("``", "_SSWEDITOR_ESCAPE_PREDICATE_"); var rPredicateMatch = Regex.Match(obj, @"\`(.+)$"); if (rPredicateMatch.Success) { parsedLine.Resource = obj.Substring(0, rPredicateMatch.Index).Replace("_SSWEDITOR_ESCAPE_PREDICATE_", "`").Trim(); parsedLine.Predicate = GetSafeFragment( rPredicateMatch.Groups[1].Value.Replace("_SSWEDITOR_ESCAPE_PREDICATE_", "`").Trim()); } else { parsedLine.Resource = obj.Replace("_SSWEDITOR_ESCAPE_PREDICATE_", "`"); } return(parsedLine); }
public void finish_with_message() { var scheduler = new TestScheduler(); var plugin = new CountdownTimer(scheduler); var pl = new ParsedLine("!countdown --duration=3 -i 1 -f I will say this when I'm done", "Bob"); long oneSecond = TimeSpan.FromSeconds(1).Ticks; ITestableObserver <string> obs = scheduler.Start(() => plugin.Evaluate(pl), 11 * oneSecond); obs.Messages.AssertEqual( OnNext(201, "3 seconds remaining..."), OnNext(10000201, "2 seconds remaining..."), OnNext(20000201, "1 second remaining..."), OnNext(30000202, "I will say this when I'm done"), OnCompleted <string>(30000202) ); }
public void count_down_from_three_seconds() { var scheduler = new TestScheduler(); var plugin = new CountdownTimer(scheduler); var pl = new ParsedLine("!countdown -d 3 -i 1", "Bob"); long oneSecond = TimeSpan.FromSeconds(1).Ticks; ITestableObserver <string> obs = scheduler.Start(() => plugin.Evaluate(pl), 11 * oneSecond); obs.Messages.AssertEqual( OnNext(201, "3 seconds remaining..."), OnNext(10000201, "2 seconds remaining..."), OnNext(20000201, "1 second remaining..."), OnNext(30000202, "Finished!"), OnCompleted <string>(30000202) ); }
protected override void OnStoryUpdate(ParsedLine line, bool visited) { if (!line.isParsed) { speakerText.text = ""; messageText.text = line.line; } else { Parse speaker = line.Find("Speaker"); if (speaker != null) { speakerText.text = speaker.value; } Parse message = line.Find("Message"); if (message != null) { messageText.text = message.value; } } }
private void FormatAndApply(ParsedLine line) { // Parse the address as hex. string FormattedAddress = line.Address.ToString("X").PadLeft(16, '0'); // Make breakpoint lines purple using markdown. No other formatting is applied to these. if ((line.Info | Emulator.AddressInfo.BREAKPOINT) == line.Info) { FormattedAddress = $"^0x{FormattedAddress}^"; } else { // Use Drawing.InsertAt..() to remove emphasis from insignificant zeroes. This is done by starting // with a low emphasis, "$" then inserting the normal emphasis, "£" at the significant digits. FormattedAddress = $"%0x%${Drawing.InsertAtNonZero(FormattedAddress, "£")}\""; } // Add some spacing between the address and disassembled line. FormattedAddress = $"{FormattedAddress} {line.DisassembledLine}"; // Replace some of that spacing if the line is the next to be executed. if ((line.Info | Emulator.AddressInfo.RIP) == line.Info) { FormattedAddress = FormattedAddress.Remove(23, 4).Insert(23, "←RIP"); } // Very similar idea to as in MemoryListView. Look there for more explanation of this. if (Items.Count - 1 < line.Index) { Items.Add(new ListViewItem(new string[] { FormattedAddress, line.Address.ToString() })); } else { Items[line.Index].Text = FormattedAddress; // Add the address as a sub item that the user will never see, but will be useful in the OnAddressClicked event. Items[line.Index].SubItems[1].Text = line.Address.ToString(); } }
public override string EvaluateEx(ParsedLine line) { if (!line.IsCommand) { return(string.Empty); } switch (line.Command.ToLower()) { case "smack": return(String.Format("{0} smacks {1} around with a large trout", line.User, line.Args.FirstOrDefault() ?? "your mom")); case "hug": return(String.Format("{0} hugs {1}", line.User, line.Args.FirstOrDefault() ?? "themself")); case "help": return(String.Format("Right now the only commands I know are !smack [thing] and !hug [thing].")); default: return(null); } }
public void encoded_urls_in_events_are_decoded() { var scheduler = new TestScheduler(); var plugin = new CountdownTimer(scheduler); var pl = new ParsedLine("!countdown --duration=5m -i 1m -e 4m http%3A%2F%2Fi.imgur.com%2FpMIpQ46.jpg", "Bob"); long oneMinute = TimeSpan.FromSeconds(60).Ticks; ITestableObserver <string> obs = scheduler.Start(() => plugin.Evaluate(pl), 6 * oneMinute); obs.Messages.AssertEqual( OnNext(201, "5 minutes remaining..."), OnNext(600000201, "4 minutes remaining..."), OnNext(1200000201, "3 minutes remaining..."), OnNext(1800000201, "2 minutes remaining..."), OnNext(2400000201, "1 minute remaining..."), OnNext(2410000201, "http://i.imgur.com/pMIpQ46.jpg"), OnNext(3010000202, "Finished!"), OnCompleted <string>(3010000202) ); }
public void five_minutes_wrap_up_reminder_at_three_and_four() { var scheduler = new TestScheduler(); var plugin = new CountdownTimer(scheduler); var pl = new ParsedLine("!countdown --duration=5m -i 1m -e 4m 1 minute warning 3m 2 minute warning", "Bob"); long oneMinute = TimeSpan.FromSeconds(60).Ticks; ITestableObserver <string> obs = scheduler.Start(() => plugin.Evaluate(pl), 6 * oneMinute); obs.Messages.AssertEqual( OnNext(201, "5 minutes remaining..."), OnNext(600000201, "4 minutes remaining..."), OnNext(1200000201, "3 minutes remaining..."), OnNext(1800000201, "2 minutes remaining..."), OnNext(1810000201, "2 minute warning"), OnNext(2400000201, "1 minute remaining..."), OnNext(2410000201, "1 minute warning"), OnNext(3010000202, "Finished!"), OnCompleted <string>(3010000202) ); }
private static IEnumerable <ScenarioCommand> ParseCommand(ParsedLine parsedLine) { /* * Possible commands: * # comment * s [sensei's line] * menu (handled elsewhere) * next * do [position] ==> shine [position] & expect [position] * white [position]... * black [position]... * clear [position]... * flash * expect [position] ==> require [position] & black [position] * shine [position] * expect_failure * suicidal_move_message * button [button_text] */ switch (parsedLine.Command) { case "s": yield return(new SayCommand(parsedLine.FullArgument)); break; case "next": yield return(new NextCommand()); break; case "do": yield return(new ShineCommand(parsedLine.FullArgument)); yield return(new RequireCommand(parsedLine.FullArgument)); yield return(new PlaceCommand(StoneColor.Black, parsedLine.FullArgument)); break; case "shine": yield return(new ShineCommand(parsedLine.FullArgument)); break; case "expect_failure": yield return(new RequireCommand(parsedLine.FullArgument)); break; case "expect": yield return(new RequireCommand(parsedLine.FullArgument)); yield return(new PlaceCommand(StoneColor.Black, parsedLine.FullArgument)); break; case "button": yield return(new ButtonNextTextCommand(parsedLine.FullArgument)); break; case "suicidal_move_message": // This should show a failure message in a pretty bubble, but we scrapped that functionality because of time constraints. break; case "black": yield return(new PlaceCommand(StoneColor.Black, parsedLine.Arguments)); break; case "white": yield return(new PlaceCommand(StoneColor.White, parsedLine.Arguments)); break; case "clear": yield return(new PlaceCommand(StoneColor.None, parsedLine.Arguments)); break; case "flash": yield return(new FlashCommand()); break; case "#": // Comment break; default: throw new Exception("This command is not implemented: " + parsedLine.Command); } }
public void TestParsedLine() { var parsedLine = new ParsedLine("this.DoSomething(firstArgument, secondArgument)"); var match = parsedLine.GetMatchingBracketForBracketAtIndex(1); if (match != 5) { throw new Exception("The matching closing bracket code item index should be 5, but it's " + match); } parsedLine.ConsolidateMethodContents(); if (parsedLine.CodeItems.Count != 2) { throw new Exception("There should only be 2 code items, but there are " + parsedLine.CodeItems.Count); } parsedLine = new ParsedLine("new Vector3()"); if (parsedLine[1].CodeType == CodeType.MethodCall) { throw new Exception("The type should be a constructor, not method call"); } parsedLine = new ParsedLine("x() + y"); if (parsedLine.CodeItems.Count != 5) { throw new Exception("There should be 5 CodeItems in the parsed line"); } parsedLine = new ParsedLine("x"); parsedLine.CombineToExpressions(); if (parsedLine.Count != 1) { throw new Exception("Error combining to expressions"); } parsedLine = new ParsedLine("x.y.z"); parsedLine.CombineToExpressions(); if (parsedLine.Count != 1) { throw new Exception("Error combining to expressions"); } parsedLine = new ParsedLine("x.y.z + a.b.c"); parsedLine.CombineToExpressions(); if (parsedLine.Count != 3) { throw new Exception("Error combining to expressions"); } parsedLine = new ParsedLine("x()"); parsedLine.CombineToExpressions(); if (parsedLine.Count != 1) { throw new Exception("Error combining to expressions"); } parsedLine = new ParsedLine("x().y"); parsedLine.CombineToExpressions(); if (parsedLine.Count != 1) { throw new Exception("Error combining to expressions"); } parsedLine = new ParsedLine("x() + y"); parsedLine.CombineToExpressions(); if (parsedLine.Count != 3) { throw new Exception("Error combining to expressions"); } parsedLine = new ParsedLine("x(3+4) + y"); parsedLine.CombineToExpressions(); if (parsedLine.Count != 3) { throw new Exception("Error combining to expressions"); } parsedLine = new ParsedLine("ToolEmitters.FindByName().Emit;"); parsedLine.ConsolidateMethodContents(); parsedLine.CombineToExpressions(); if (parsedLine.Count != 2) { throw new Exception("Error combining to expressions"); } }
public void templateNestedBadThings() { ParsedLine line = new ParsedLine("template<template<template<unsigned long long int>>> template<template<template<unsigned long long int>>>::testFunc(template<template<template<unsigned long long int>>>, template<template<template<unsigned long long int>>>***, template<template<template<unsigned long long int>>>&)"); ParsedClass theClass = new ParsedClass(line); ParsedFunction func = new ParsedFunction(line, theClass); }
public void templatedClassNameSpace() { ParsedLine line = new ParsedLine("template<unsigned long long int>::testFunc()"); ParsedClass theClass = new ParsedClass(line); ParsedFunction func = new ParsedFunction(line, theClass); Assert.IsTrue(func.parentClass.name == SymbolParser.SymbolParser.handleTemplatedName("template<unsignedlonglongint>"), "Return type was invalid."); }
public void NoReturnTypeFreeStandingFunction() { ParsedLine line = new ParsedLine("testFunction() 0xFFFFFFFF"); ParsedClass theClass = new ParsedClass(line); ParsedFunction func = new ParsedFunction(line, theClass); bool decorators = !func.accessLevel.HasValue && !func.isStatic && !func.isVirtual && !func.isConstructor && !func.isDestructor && !func.callingConvention.HasValue; if (!decorators) { Assert.Fail("Decorators failed to pass"); } Assert.IsTrue(func.returnType == null, "Return type failed to pass."); Assert.IsTrue(func.parameters.Count == 0, "Param count failed to pass"); bool names = func.parentClass.name == ParsedClass.FREE_STANDING_CLASS_NAME && func.name == "testFunction"; if (!names) { Assert.Fail("Names failed to pass"); } bool end = !func.isConst && func.address == 0xFFFFFFFF; if (!end) { Assert.Fail("End failed to pass"); } }
public bool Equals(ParsedLine other) { if (ReferenceEquals(null, other)) return false; if (ReferenceEquals(this, other)) return true; return other.Line == Line && Equals(other.Text, Text); }
public void Types() { ParsedLine line = new ParsedLine("CExoLinkedList<unsigned long>::AddTail(unsigned long *) 0x80B1670"); ParsedClass theClass = new ParsedClass(line); ParsedFunction func = new ParsedFunction(line, theClass); }
public UpdateLineEvent(ParsedLine parse, bool visited) { this.parse = parse; this.visited = visited; }
public void SetMainLine(string line) { IsParameter = char.IsWhiteSpace(line[0]); mainLine = line; parsedLine = ParsedLine.ParseLine(line); }
public ParsedFunction(ParsedLine line, ParsedClass theClass, List<ParsedTypedef> typedefs) { name = SymbolParser.handleTemplatedName(line.functionName); if (theClass != null) { parentClass = theClass; accessLevel = stringToAccessLevel(line.accessLevel); int templateIndex = theClass.name.IndexOf("Templated", StringComparison.Ordinal); if (templateIndex != -1) { // This is a template. Let's check for template ctor/dtor names. string className = parentClass.name.Substring(0, templateIndex); if (name == className) { name = theClass.name; isConstructor = true; } else if (name == "~" + className) { name = theClass.name; isDestructor = true; } } if (name == parentClass.name) { isConstructor = true; } else if (name == "~" + parentClass.name) { isDestructor = true; } isVirtual = line.isVirtual; isConst = line.isConst; } isStatic = line.isStatic; friendlyName = makeFriendlyName(); if (line.returnType != null) { returnType = new CppType(SymbolParser.handleTemplatedName(line.returnType), typedefs); } parameters = new List<CppType>(); foreach (string parameter in line.parameters.Split(',')) { CppType param = new CppType(SymbolParser.handleTemplatedName(parameter), typedefs); if (!param.isBaseType || param.isPointer || (param.baseType.HasValue && param.baseType.Value != BuiltInCppTypes.VOID)) { parameters.Add(param); } } callingConvention = stringToCallingConv(line.callingConvention); address = Convert.ToUInt32(line.address, 16); }
public static TemplateParameter ParseParameter(ParsedLine line) { int minDimensions = 1; int maxDimensions = 1; bool pointer = false; bool isFixed = false; bool signed = false; int prefBase = 16; Priority pointedPriority = Priority.none; foreach (string item in line.flags) { if (item.Length == 0) { continue; } int index = item.IndexOf(':'); if (item.StartsWith("pointer")) { pointer = true; if (index > 0) { string priority = item.Substring(index + 1); if (Enum.GetNames(typeof(Priority)).Contains(priority)) { pointedPriority = (Priority)Enum.Parse(typeof(Priority), priority); } } } else if (item.StartsWith("coordinates") || item.StartsWith("coordinate")) { if (index < 0) throw new FormatException("No : in option " + item); string dimensionsS = item.Substring(index + 1); if (dimensionsS.Contains("-")) { string[] dimensionsSS = dimensionsS.Split('-'); minDimensions = int.Parse(dimensionsSS[0]); maxDimensions = int.Parse(dimensionsSS[1]); } else { int dimensions = int.Parse(dimensionsS); minDimensions = dimensions; maxDimensions = dimensions; } } else if (item.StartsWith("preferredBase")) { if (index < 0) throw new FormatException("No : in option " + item); string valueS = item.Substring(index + 1); prefBase = valueS.GetValue(); } else if (item.StartsWith("fixed")) { isFixed = true; } else if (item.StartsWith("signed")) { signed = true; } else { throw new FormatException("Unknown option " + item + " in parameter " + line.name); } } TemplateParameter param = new TemplateParameter(line.name, line.number1, line.number2, minDimensions, maxDimensions, pointer, pointedPriority, signed, isFixed, prefBase); return param; }
public static ParsedLine ParseLine(string line) { ParsedLine parsedLine = new ParsedLine(); string[] split = line.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); parsedLine.name = split[0].Trim(); parsedLine.number1 = StringExtensions.GetValue(split[1].Trim()); parsedLine.number2 = StringExtensions.GetValue(split[2].Trim()); if (split.Length > 3) { List<string> options = new List<string>(split[3].Split(" -".GetArray(), StringSplitOptions.RemoveEmptyEntries)); for (int i = 0; i < options.Count; i++) { options[i] = options[i].Trim(); } parsedLine.flags = options.ToArray(); } else { parsedLine.flags = new string[0]; } return parsedLine; }
public ParsedClass(ParsedLine parsedLine) : this(SymbolParser.handleTemplatedName(parsedLine.className)) { }
private bool ParseLine(string line, ParsedLine parsedLine, List <string> recursiveWords = null, ConcatAction?lastAction = null) { List <string> words; if (recursiveWords == null) { words = line.Split(new[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries).ToList(); if (words.Count == 0) { parsedLine.LineState = LineState.Empty; return(true); } } else { words = recursiveWords; } if (parsedLine.LineState == LineState.Begin) { var cmd = GetCommand(words[0]); if (cmd == Command.UnknownCommand) { parsedLine.ErrorMsg = $"Unknown command: `{words[0]}`"; return(false); } ParsedCommand parsedCommand = new ParsedCommand { Command = cmd }; parsedLine.ParsedCommands.Add(parsedCommand); parsedLine.LineState = LineState.AfterCommand; words.RemoveAt(0); if (lastAction != null) { parsedLine.ParsedCommands.Last().PrevConcatAction = lastAction.Value; lastAction = null; } if (words.Count == 0) { if (_actions[parsedLine.ParsedCommands.Last().Command].NumOfArgs > 0) { parsedLine.ErrorMsg = $"Missing argument(s) after command : {parsedLine.ParsedCommands.Last().Command} (should get at least {_actions[parsedLine.ParsedCommands.Last().Command].NumOfArgs} arguments but got none)"; return(false); } return(true); } } if (parsedLine.LineState == LineState.AfterCommand) { var args = new List <string>(); int i; for (i = 0; i < words.Count; i++) { if (i == 0) { if (_actions.ContainsKey(parsedLine.ParsedCommands.Last().Command) == false) { parsedLine.ErrorMsg = $"Internal CLI Error : no definition for `{parsedLine.ParsedCommands.Last().Command}`"; return(false); } switch (words[0]) { case "&&": case "||": if (_actions[parsedLine.ParsedCommands.Last().Command].NumOfArgs != 0) { parsedLine.ErrorMsg = $"Missing argument(s) after command : {parsedLine.ParsedCommands.Last().Command}"; return(false); } break; } } if (words[i] != "&&" && words[i] != "||") { args.Add(words[i]); continue; } if (words[i] == "&&") { parsedLine.LineState = LineState.AfterArgs; lastAction = ConcatAction.And; break; } if (words[i] == "||") { parsedLine.LineState = LineState.AfterArgs; lastAction = ConcatAction.Or; break; } // cannot reach here parsedLine.ErrorMsg = "Internal CLI Error"; return(false); } parsedLine.ParsedCommands.Last().Args = args; if (lastAction == null) { if (args.Count < _actions[parsedLine.ParsedCommands.Last().Command].NumOfArgs) { parsedLine.ErrorMsg = $"Missing argument(s) after command : {parsedLine.ParsedCommands.Last().Command} (should get at least {_actions[parsedLine.ParsedCommands.Last().Command].NumOfArgs} arguments but got {args.Count})"; return(false); } return(true); } List <string> newWords = new List <string>(); for (int j = i + 1; j < words.Count; j++) { newWords.Add(words[j]); } parsedLine.LineState = LineState.Begin; return(ParseLine(null, parsedLine, newWords, lastAction)); } return(true); }
public void templateReturnType() { ParsedLine line = new ParsedLine("template<templateInner> testFunc()"); ParsedClass theClass = new ParsedClass(line); ParsedFunction func = new ParsedFunction(line, theClass); Assert.IsTrue(func.returnType.type == SymbolParser.SymbolParser.handleTemplatedName("template<templateInner>"), "Return type was invalid."); }
private bool StartCli() { var ctrlCPressed = false; if (_consoleColoring) { Console.CancelKeyPress += (sender, args) => { Console.ResetColor(); ctrlCPressed = true; } } ; else { new WelcomeMessage(_writer).Print(); // beware not to print any delimiters until reaching PrintCliHeader _writer.WriteLine("Connected to RavenDB Console through named pipe connection..." + Environment.NewLine); _writer.Write(GetDelimiterString(Delimiter.ContinuePrinting)); _writer.Flush(); } while (true) { PrintCliHeader(this); var line = ReadLine(this); _writer.Flush(); if (line == null) { if (_consoleColoring == false) { // for some reason remote pipe couldn't ReadLine WriteText("End of standard input detected. Remote console might not support input", ErrorColor, this); // simulate logout: line = "logout"; } else { Thread.Sleep(75); //waiting for Ctrl+C if (ctrlCPressed) { break; } WriteText("End of standard input detected, switching to server mode...", WarningColor, this); Program.RunAsNonInteractive(); return(false); } } var parsedLine = new ParsedLine { LineState = LineState.Begin }; if (ParseLine(line, parsedLine) == false) { WriteError(parsedLine.ErrorMsg, this); continue; } if (parsedLine.LineState == LineState.Empty) { continue; } var lastRc = true; foreach (var parsedCommand in parsedLine.ParsedCommands) { if (lastRc == false) { if (parsedCommand.PrevConcatAction == ConcatAction.And) { WriteWarning($"Warning: Will not execute command `{parsedCommand.Command}` as previous command return non-successful return code", this); break; } WriteWarning($"Warning: Will execute command `{parsedCommand.Command}` after previous command return non-successful return code", this); } if (_actions.ContainsKey(parsedCommand.Command) == false) { WriteError($"CLI Internal Error (missing definition for the command: {parsedCommand.Command})", this); lastRc = false; continue; } var cmd = _actions[parsedCommand.Command]; try { if (cmd.Experimental) { if (_experimental == false) { WriteError($"{parsedCommand.Command} is experimental, and can be executed only if expermintal option set to on", this); lastRc = false; continue; } WriteText("", TextColor, this); WriteText("Are you sure you want to run experimental command : " + parsedCommand.Command + " ? [y/N] ", WarningColor, this, newLine: false); var k = ReadKey(this); WriteText("", TextColor, this); if (char.ToLower(k).Equals('y') == false) { lastRc = false; continue; } } lastRc = cmd.DelegateFync.Invoke(parsedCommand.Args, this); if (parsedCommand.Command == Command.Prompt && lastRc) { _promptArgs = parsedCommand.Args; } else if (parsedCommand.Command == Command.Experimental) { _experimental = lastRc; lastRc = true; } } catch (Exception ex) { WriteError(ex.ToString(), this); break; } if (lastRc) { if (parsedCommand.Command == Command.ResetServer) { if (Program.IsRunningNonInteractive || _writer == Console.Out) { if (_consoleColoring == false) { const string str = "Restarting Server"; PrintBothToConsoleAndRemotePipe(str, this, Delimiter.RestartServer); } return(true); } WriteText("Server is not running as Service. Restarting from a remote connection is not allowed." + Environment.NewLine + "Please restart the server from its main console" + Environment.NewLine, WarningColor, this); } if (parsedCommand.Command == Command.Shutdown) { if (Program.IsRunningNonInteractive || _writer == Console.Out) { if (_consoleColoring == false) { const string str = "Shutting down the server"; PrintBothToConsoleAndRemotePipe(str, this, Delimiter.Shutdown); } return(false); } WriteText("Server is not running as Service. Shutting down from a remote connection is not allowed." + Environment.NewLine + "Please shutdown the server from its main console" + Environment.NewLine, WarningColor, this); } if (parsedCommand.Command == Command.Logout) { break; } } else { if (parsedCommand.Command == Command.Shutdown || parsedCommand.Command == Command.ResetServer) { lastRc = true; // if answered "No" for the above command - don't print ERROR } } } if (lastRc == false) { WriteError("Command Failed", this); } } _writer.Flush(); // we are logging out from cli Debug.Assert(_consoleColoring == false); return(false); }
public ParsedLine(ParsedLine toChangeTo, AddressInfo toXor = 0) { this = toChangeTo; Info ^= toXor; }
public void templateClassType() { ParsedLine line = new ParsedLine("template<templateInner>::testFunc()"); ParsedClass theClass = new ParsedClass(line); ParsedFunction func = new ParsedFunction(line, theClass); Assert.IsTrue(func.parentClass.name == SymbolParser.SymbolParser.handleTemplatedName("template<templateInner>"), "Class name was invalid."); }
public void templateParamType() { ParsedLine line = new ParsedLine("testFunc(template<templateInner>)"); ParsedClass theClass = new ParsedClass(line); ParsedFunction func = new ParsedFunction(line, theClass); Assert.IsTrue(func.parameters[0].type == SymbolParser.SymbolParser.handleTemplatedName("template<templateInner>"), "Params type was invalid."); }
protected abstract void OnStoryUpdate(ParsedLine parse, bool visited);
public void FreeStandingFunctionParams() { ParsedLine line = new ParsedLine("unsigned long long int testFunction(unsigned char*** const, const bool, UserType&) 0xFFFFFFFF"); ParsedClass theClass = new ParsedClass(line); ParsedFunction func = new ParsedFunction(line, theClass); bool decorators = !func.accessLevel.HasValue && !func.isStatic && !func.isVirtual && !func.isConstructor && !func.isDestructor && !func.callingConvention.HasValue; if (!decorators) { Assert.Fail("Decorators failed to pass"); } bool returnType = func.returnType.isBaseType && func.returnType.baseType.Value == BuiltInCppTypes.UNSIGNED_LONG_LONG_INT && func.returnType.type == "unsigned long long int" && !func.returnType.isConst && !func.returnType.isPointer && !func.returnType.isConstPointer && !func.returnType.isReference; if (!returnType) { Assert.Fail("Return type failed to pass"); } bool names = func.parentClass.name == ParsedClass.FREE_STANDING_CLASS_NAME && func.name == "testFunction"; if (!names) { Assert.Fail("Names failed to pass"); } Assert.IsTrue(func.parameters.Count == 3, "Param count failed to pass"); bool param1 = func.parameters[0].isBaseType && func.parameters[0].baseType.Value == BuiltInCppTypes.UNSIGNED_CHAR && func.parameters[0].type == "unsigned char" && !func.parameters[0].isConst && func.parameters[0].isPointer && func.parameters[0].pointerDepth == 3 && func.parameters[0].isConstPointer && !func.parameters[0].isReference; if (!param1) { Assert.Fail("Param1 failed to pass"); } bool param2 = func.parameters[1].isBaseType && func.parameters[1].baseType.Value == BuiltInCppTypes.BOOL && func.parameters[1].type == "bool" && func.parameters[1].isConst && !func.parameters[1].isPointer && !func.parameters[1].isConstPointer && !func.parameters[1].isReference; if (!param2) { Assert.Fail("Param2 failed to pass"); } bool param3 = !func.parameters[2].isBaseType && func.parameters[2].type == "UserType" && !func.parameters[2].isConst && !func.parameters[2].isPointer && !func.parameters[2].isConstPointer && func.parameters[2].isReference; if (!param3) { Assert.Fail("Param3 failed to pass"); } bool end = !func.isConst && func.address == 0xFFFFFFFF; if (!end) { Assert.Fail("End failed to pass"); } }