public XmlGrammar() : base("xml") { EnableMatchEvents = false; var comment = new GroupParser("<!--", "-->"); var ws = Terminals.Repeat(Char.IsWhiteSpace, 1); var ows = Terminals.Repeat(Char.IsWhiteSpace, 0); var wsc = -(ws | comment); var name = Terminals.Repeat(new RepeatCharItem(Char.IsLetter, 1, 1), new RepeatCharItem(Char.IsLetterOrDigit, 0)); var namedName = Terminals.Repeat(new RepeatCharItem(Char.IsLetter, 1, 1), new RepeatCharItem(Char.IsLetterOrDigit, 0)).WithName("name"); var text = new UntilParser("<", 1).WithName("text"); var attributeValue = new StringParser { QuoteCharacters = new [] { '"' }, Name = "value" }; var attribute = (namedName & ows & "=" & ows & attributeValue); var attributes = (ws & (+attribute).SeparatedBy(ws).WithName("attributes")).Optional(); var content = new RepeatParser { Separator = wsc }; var startTag = "<" & namedName & attributes & ows; var endTag = "</" & name & ">"; var obj = (startTag & ("/>" | (">" & wsc & content & wsc & endTag))).WithName("object"); var cdata = ("<![CDATA[" & new UntilParser("]]>", 0, skip: true)).WithName("cdata"); content.Inner = obj | text | cdata; var declaration = "<?" & name & attributes & ows & "?>"; Inner = declaration & wsc & obj & wsc; }
public static RepeatParser Until(this RepeatParser parser, Parser until, bool skip = false, bool capture = false) { parser.Until = until; parser.SkipUntil = skip; parser.CaptureUntil = capture; return(parser); }
public Syntax() : base("RuleForse-script") { runners = new List <RunBase>(); #region special symbols var WS = -Terminals.WhiteSpace; var Terminaler = -Terminals.Set(';'); #endregion #region reserved words var rwDeclare = "declare"; var rwDictionary = "dictionary"; var rwDocument = "document"; var rwField = "field"; var rwOf = "of"; var rwSelect = "select"; var rwKnowledge = "knowledge"; var rwData = "data"; var rwFrom = "from"; #endregion var Name = Terminals.Repeat(new RepeatCharItem(Char.IsLetter, 1, 1), new RepeatCharItem(Char.IsLetterOrDigit, 0)).WithName("name"); var Name1 = +Terminals.LetterOrDigit.WithName("name1"); var ObjectName = Terminals.Repeat(new RepeatCharItem(Char.IsLetter, 1, 1), new RepeatCharItem(Char.IsLetterOrDigit, 0)).WithName("objectName"); var Command = new RepeatParser { Separator = Terminaler }; #region declare var DeclareDictionary = (WS & rwDeclare & WS & rwDictionary & WS & Name & WS).WithName("declare dictionary"); DeclareDictionary.Matched += (match) => { runners.Add(new RunDeclareDictionary(match)); }; var DeclareDocument = (WS & rwDeclare & WS & rwDocument & WS & Name & WS).WithName("declare document"); DeclareDocument.Matched += (match) => { runners.Add(new RunDeclareDocument(match)); }; var DeclareField = (WS & rwDeclare & WS & rwField & WS & Name & WS & rwOf & WS & ObjectName).WithName("declare field"); DeclareField.Matched += (match) => { runners.Add(new RunDeclareField(match)); }; #endregion #region select var SelectKnowledge = (WS & rwSelect & WS & rwKnowledge).WithName("select knowledge"); var SelectData = (WS & rwSelect & WS & rwData & WS & rwFrom & ObjectName).WithName("select data"); #endregion Command.Inner = DeclareDictionary | DeclareDocument | DeclareField | SelectKnowledge | SelectData; Inner = Command & Terminaler; }
Parser Primary(Match match, bool isTerminal) { var child = match.Matches.FirstOrDefault(r => r.Name != null); if (child == null) { throw new FormatException(string.Format("Primary must have a child. Text: '{0}'", match.Text)); } Parser parser; switch (child.Name) { case "grouped sequence": return(new UnaryParser(DefinitionList(child["definition list"], isTerminal))); case "optional sequence": return(new OptionalParser(DefinitionList(child["definition list"], isTerminal))); case "repeated sequence": var repeat = new RepeatParser(DefinitionList(child["definition list"], isTerminal), 0); if (!isTerminal) { repeat.Separator = separator; } return(repeat); case "meta identifier": if (!parserLookup.TryGetValue(child.Text, out parser)) { parser = parserLookup[child.Text] = Terminals.LetterOrDigit.Repeat().Named(child.Text); } return(parser); case "terminal string": return(new LiteralTerminal(child.StringValue)); case "hex character": return(new SingleCharTerminal((char)int.Parse(child.Text.Substring(2), NumberStyles.HexNumber))); case "character set": return(CharacterSet(child)); case "special sequence": var name = child["name"].Text.Trim(); if (specialLookup.TryGetValue(name, out parser)) { return(parser); } else { return(null); } default: throw new FormatException(string.Format("Could not parse child with name '{0}'", child.Name)); } }
public void SetUp() { parser = P.Repeat <string, string>( P.Literal("asd"), Quantification.Plus ) .Process(p => String.Concat(p.Matches.Select(m => m.Value))) .CreateParser(); }
public void Initialize(MarkdownGrammar grammar) { var content = new RepeatParser().Until(Terms.eolorf); content.Name = "content"; var line = grammar.Indent & content; Inner = line; this.Minimum = 1; this.SeparatedBy(+(Terms.ows & Terms.eol.Named("sep"))).Until(Terms.EndOfSection(line.Not()), true); }
public void Initialize(MarkdownGrammar grammar) { this.grammar = grammar; var prefix = (grammar.Prefix & -Terms.sp) & Terminals.Literal(">"); var value = new RepeatParser(1).Until(Terms.eolorf, true); prefix.Name = "prefix"; value.Name = "value"; this.Inner = prefix.Separate() & Terms.ows & value & -Terms.blankLine; this.Minimum = 1; }
public void ItFailsWithTooFewOccurences() { parser = P.Repeat <string, string>( P.Literal("asd"), Quantification.AtLeast(5) ).CreateParser(); parser.Parse("asd"); Assert.False(parser.Success); Assert.AreEqual(1, parser.MatchCount); }
Parser Primary(Match match, bool isTerminal) { var child = match.Matches.FirstOrDefault(); if (child == null) { return(null); } Parser parser; switch (child.Name) { case "grouped sequence": return(new UnaryParser(DefinitionList(child["definition list"], isTerminal))); case "optional sequence": return(new OptionalParser(DefinitionList(child["definition list"], isTerminal))); case "repeated sequence": var repeat = new RepeatParser(DefinitionList(child["definition list"], isTerminal), 0); if (!isTerminal) { repeat.Separator = separator; } return(repeat); case "meta identifier": if (!parserLookup.TryGetValue(child.Text, out parser)) { parser = parserLookup[child.Text] = Terminals.LetterOrDigit.Repeat().Named(child.Text); } return(parser); case "terminal string": return(new LiteralTerminal(child["value"].Text)); case "special sequence": var name = child["name"].Text.Trim(); if (specialLookup.TryGetValue(name, out parser)) { return(parser); } else { return(null); } default: return(null); } }
public AddressGrammar() : base("postal-address") { RepeatParser terminal = +Terminals.LetterOrDigit; Parser aptNum = (((Parser)"Apt" | "Suite") & "#" & +Terminals.Digit).Named("apt-num"); Parser streetType = ((Parser)"Street" | "Drive" | "Ave" | "Avenue").Named("street-type"); Parser street = (terminal.Named("street-name") & ~streetType).Named("street"); Parser zipPart = (terminal.Named("town-name") & "," & terminal.Named("state-code") & terminal.Named("zip-code")).Named( "zip"); Parser streetAddress = (terminal.Named("house-num") & street & aptNum).Named("street-address"); // name Parser suffixPart = ((Parser)"Sr." | "Jr." | +Terminals.Set("IVXLCDM")).Named("suffix"); Parser personalPart = (terminal.Named("first-name") | (Terminals.Letter & ".")).Named("personal"); var namePart = new UnaryParser("name"); namePart.Inner = (personalPart & terminal.Named("last-name") & ~suffixPart) | (personalPart & namePart); // recursion Inner = namePart & Terminals.Eol & streetAddress & ~Terminals.Eol & zipPart; }
public MarkdownGrammar() : base("markdown") { EnableMatchEvents = false; indent = new RepeatParser(Terms.indent, 1, 1); prefix = new RepeatParser(Terms.indent, 0, 0); prefixsp = new RepeatParser(Terms.sporht, 0, 0); encoding = new MarkdownEncoding(); encoding.Initialize(this); replacementsOnly = new ReplacementParser(this); replacements = new ReplacementParser(this); var reps = GetReplacements().ToArray(); replacementsOnly.Add(reps, false); replacements.Add(reps, true); replacements.Add(Terminals.AnyChar); this.Inner = -replacements; SetError <Parser>(false); }
Parser Factor(Match match, bool isTerminal) { var primary = Primary(match["primary"], isTerminal); var cardinality = match["cardinality"]; if (cardinality) { switch (cardinality.Text) { case "?": primary = new OptionalParser(primary); break; case "*": primary = new RepeatParser(primary, 0); break; case "+": primary = new RepeatParser(primary, 1); break; default: throw new FormatException(string.Format("Cardinality '{0}' is unknown", cardinality.Text)); break; } } var integer = match["integer"]; if (integer) { return(new RepeatParser(primary, Int32.Parse(integer.Text))); } else { return(primary); } }
public static RepeatParser Until(this RepeatParser parser, Parser until) { parser.Until = until; return(parser); }
public RepeaterModel GetRepeatingModel() { RepeaterModel model = new RepeaterModel(); var filter = new IssuesFilter(); if (IsSessionFilter() || !CurrentCard.Options.ContainsKey(AppGuid)) { filter = HttpSessionManager.GetFilter(CurrentCard.Id, IssuesFilter.CreateProjectFilter(CurrentUser.Entity.Id, CurrentProject.Entity.Id)); } else if (CurrentCard.Options.ContainsKey(AppGuid)) { filter = CurrentCard.Options[AppGuid].FromJson <IssuesFilter>(); } else { filter = CurrentCard.Filter; } if (filter.Repeat.IsEmpty() || filter.Repeat == "-|3") { filter.Repeat = "-|1"; } var transformedFilter = ItemFilterManager.TransformFilter(filter); SetCurrentProjectFromFilter(transformedFilter); model.Filter = IssueFilterHelper.PopulateModel(model.Filter, filter, transformedFilter, PermissionsManager, ItemFilterManager, IssueFilterHelper.GetViewableFields(filter, ProjectManager, MetaManager), false); model.GeminiDateFormat = CurrentUser.GeminiDateFormat; model.BaseUrl = string.Format("{0}workspace/{1}/", UserContext.Url, CurrentCard.Id); var allIssues = IssueManager.GetFiltered(filter); var allIssuesRelatedRepeating = allIssues.Count > 0 ? allIssues.FindAll(s => s.Repeated.HasValue() || s.Entity.OriginatorData.HasValue() && s.Entity.OriginatorType == IssueOriginatorType.Repeat) : new List <IssueDto>(); var masterIssues = allIssuesRelatedRepeating.Count > 0 ? allIssuesRelatedRepeating.FindAll(i => i.Repeated.HasValue()) : new List <IssueDto>(); List <string> repeatValues = new List <string>(); repeatValues.Add("-|1"); repeatValues.Add("-|2"); repeatValues.Add("-|3"); int totalNumberOfRepeatedItems = 0; if (masterIssues.Count > 0) { foreach (var masterIssue in masterIssues) { ItemsGrid item = new ItemsGrid(); item.MasterItem = masterIssue; item.RepeatedItems = allIssuesRelatedRepeating.FindAll(s => s.OriginatorData.HasValue() && s.OriginatorData.Equals(masterIssue.Entity.Id.ToString())); if (item.RepeatedItems.Count > 0 || filter.Repeat == "-|2" || !repeatValues.Contains(filter.Repeat)) { item.RepeatedItems = item.RepeatedItems.OrderBy("Created").ToList(); IssueDto lastRepeated = IssueManager.GetLastCreatedIssueForOriginator(IssueOriginatorType.Repeat, masterIssue.Id.ToString()); if (lastRepeated != null) { item.LastRepitition = lastRepeated.Created.ToString(UserContext.User.DateFormat); } } //Create Next repitition RepeatParser repeat = new RepeatParser(masterIssue.Repeated); for (DateTime date = DateTime.Today; item.NextRepitition.IsEmpty(); date = date.AddDays(1)) { repeat.CurrentDateTime = date; DateTime lastRepeatedDate = masterIssue.Created; if (item.RepeatedItems.Count > 0) { lastRepeatedDate = item.RepeatedItems.Last().Entity.Created; } if (item.RepeatedItems.Count >= repeat.MaximumRepeats) { break; } if (repeat.NeedsToRepeat(lastRepeatedDate)) { item.NextRepitition = date.ToShortDateString(); break; } } totalNumberOfRepeatedItems += item.RepeatedItems.Count; model.Items.Add(item); } } else if (allIssuesRelatedRepeating.Count > 0) { foreach (var repeatedIssue in allIssuesRelatedRepeating) { ItemsGrid item = new ItemsGrid() { MasterItem = repeatedIssue, RepeatedItems = new List <IssueDto>() }; model.Items.Add(item); } } model.ItemCount = masterIssues.Count + totalNumberOfRepeatedItems; return(model); }
public ActionResult Create(string startDate, string endDate, int itemId) { DateTime?startDateTime = ParseDateString.GetDateForString(startDate); DateTime?endDateTime = ParseDateString.GetDateForString(endDate); if (startDateTime == null || endDateTime == null || endDateTime < startDateTime) { return(JsonError("Make sure Start Date and End Date are valid dates")); } //If selection range is bigger than 3 years set the last date to max 3 years if (((endDateTime.Value - DateTime.Today).TotalDays / 365) > 3) { endDateTime = DateTime.Today.AddYears(3); if (startDateTime > endDateTime) { startDateTime = endDateTime; } } var closedStatuses = MetaManager.StatusGetClosed(); List <IssueLinkType> linkTypes = IssueManager.GeminiContext.Meta.LinkTypeGet(); IssueLinkType repeatedLinkType = linkTypes.Find(t => string.Compare(t.Label, "Repeated", true) == 0); if (repeatedLinkType == null && linkTypes.Count > 0) { repeatedLinkType = linkTypes[0]; } var issue = IssueManager.Get(itemId); RepeatParser repeat = new RepeatParser(issue.Repeated); List <IssueDto> repeatedIssues = IssueManager.GetItemsForOriginator(IssueOriginatorType.Repeat, issue.Id.ToString()); if (repeatedIssues.Count > 0) { var previousItemsToDelete = repeatedIssues.FindAll(c => c.Created.Date() >= startDateTime.Value && c.Created.Date() <= endDateTime.Value && !closedStatuses.Contains(c.Entity.StatusId)); foreach (var item in previousItemsToDelete) { IssueManager.Delete(item.Entity.Id); } } for (DateTime date = startDateTime.Value; date <= endDateTime.Value; date = date.AddDays(1)) { repeat.CurrentDateTime = date.Date(); IssueDto lastRepeated = IssueManager.GetLastCreatedIssueForOriginator(IssueOriginatorType.Repeat, issue.Id.ToString()); DateTime lastRepeatedDate = issue.Created; if (lastRepeated != null && lastRepeated.Entity.IsExisting) { lastRepeatedDate = lastRepeated.Created; } if (repeat.MaximumRepeats > 0) { repeatedIssues = IssueManager.GetItemsForOriginator(IssueOriginatorType.Repeat, issue.Id.ToString()); if (repeatedIssues != null && repeatedIssues.Count >= repeat.MaximumRepeats) { continue; } } //If last item was created into the future do this if (lastRepeatedDate > date.Date()) { List <IssueDto> tmpRepeatedIssues = IssueManager.GetItemsForOriginator(IssueOriginatorType.Repeat, issue.Id.ToString()); List <IssueDto> ItemsBeforeStartDate = tmpRepeatedIssues.FindAll(i => i.Created < date.Date()); if (ItemsBeforeStartDate.Count == 0) { lastRepeatedDate = issue.Created; } else { lastRepeatedDate = ItemsBeforeStartDate.OrderBy("Created").Last().Created; } } if (repeat.NeedsToRepeat(lastRepeatedDate)) { var customFields = issue.CustomFields; issue.Attachments = new List <IssueAttachmentDto>(); issue.Entity.Repeated = string.Empty; issue.Entity.OriginatorData = issue.Entity.Id.ToString(); issue.Entity.OriginatorType = IssueOriginatorType.Repeat; issue.Entity.ParentIssueId = null; issue.Entity.IsParent = false; issue.Entity.StatusId = 0; issue.Entity.ResolutionId = 0; if (issue.Entity.StartDate.HasValue && issue.Entity.DueDate.HasValue && issue.Entity.StartDate != new DateTime() && issue.Entity.DueDate != new DateTime()) { TimeSpan tsDates = issue.Entity.DueDate.Value - issue.Entity.StartDate.Value; issue.Entity.DueDate = date.AddDays(tsDates.TotalDays); issue.Entity.StartDate = date.Date(); } else { issue.Entity.StartDate = null; issue.Entity.DueDate = null; } int issueId = issue.Id; issue.Entity.Created = date; IssueDto repeated = IssueManager.Create(issue.Entity); if (repeated.Entity.Id > 0) { string statment = "update gemini_issues set created = @created where issueid = @issueid"; SQLService.Instance.ExecuteQuery(statment, new { created = new DateTime(date.Year, date.Month, date.Day, 8, 0, 0).ToUtc(UserContext.User.TimeZone), issueid = repeated.Entity.Id }); } if (customFields != null && customFields.Count > 0) { foreach (var field in customFields) { try { //Find the existing ID to 'replace', if exists. var existingCF = repeated.CustomFields .SingleOrDefault(s => s.Entity.CustomFieldId == field.Entity.CustomFieldId); field.Entity.Id = existingCF == null ? 0 : existingCF.Entity.Id; field.Entity.IssueId = repeated.Entity.Id; field.Entity.ProjectId = repeated.Entity.ProjectId; CustomFieldManager.Update(new CustomFieldData(field.Entity)); } catch (Exception ex) { LogException(ex); } } } if (repeatedLinkType != null) { IssueManager.IssueLinkCreate(repeated.Entity.Id, issueId, repeatedLinkType.Id); } } } return(JsonSuccess()); }
void FixRecursiveGrammars() { var empty = new EmptyParser(); var alternates = Children.OfType <AlternativeParser>(); var first = new List <Parser>(); var second = new List <Parser>(); foreach (var alt in alternates.Distinct().ToList()) { first.Clear(); second.Clear(); Parser separator = null; for (int i = 0; i < alt.Items.Count; i++) { Parser item = alt.Items[i]; if (item != null && item.IsLeftRecursive(alt)) { var seqs = item.Scan(filter: p => { if (ReferenceEquals(p, alt)) { return(false); } if (p is SequenceParser seq && seq.Items.Count > 0 && seq.Items[0].IsLeftRecursive(alt)) { seq.Items[0] = empty; return(true); } return(false); }).OfType <SequenceParser>(); foreach (var seq in seqs) { separator = seq.Separator; seq.Items.RemoveAt(0); } if (!item.IsLeftRecursive(alt)) { second.Add(item); } else { Debug.WriteLine(string.Format("Warning: Item in alternate is still recursive {0}", item.DescriptiveName)); } } else { first.Add(item); } } if (second.Count > 0) { Debug.WriteLine(string.Format("Fixing recursion in alternate: {0}", alt.DescriptiveName)); alt.Items.Clear(); var secondParser = second.Count > 1 ? new AlternativeParser(second) : second[0]; if (first.Count > 0) { var firstParser = first.Count > 1 ? new AlternativeParser(first) : first[0]; var repeat = new RepeatParser(secondParser, 0) { Separator = separator }; if (first.Count == 1 && first[0] == null) { alt.Items.Add(repeat); } else { alt.Items.Add(new SequenceParser(firstParser, repeat) { Separator = separator }); } } else { alt.Items.Add(new RepeatParser(secondParser, 1) { Separator = separator }); } } } }
public EbnfGrammar(EbnfStyle style) : base("ebnf") { Style = style; DefineCommonNonTerminals = true; GenerateSpecialSequences(); // terminals var comment = style.HasFlag(EbnfStyle.BracketComments) ? new GroupParser("(*", "*)") : new GroupParser("/*", "*/"); var ows = -(Terminals.WhiteSpace | comment); var rws = +(Terminals.WhiteSpace | comment); var hex_character = ("#x" & +Terminals.HexDigit); var character = (("\\" & Terminals.AnyChar) | hex_character | Terminals.AnyChar.Except("]")).WithName("character"); var character_range = (character & "-" & character).WithName("character range"); var character_set = ("[" & ~(Parser)"^" & +(character_range | character) & "]").WithName("character set"); var terminal_string = new StringParser { QuoteCharacters = new [] { '\"', '\'', '’' }, Name = "terminal string" }; var special_sequence = ("?" & (+Terminals.AnyChar).Until("?").WithName("name") & "?").WithName("special sequence"); var meta_identifier_terminal = Terminals.Letter & -(Terminals.LetterOrDigit | '_'); var integer = new NumberParser().WithName("integer"); // nonterminals var definition_list = new RepeatParser(0).WithName("definition list"); var single_definition = new RepeatParser(1).WithName("single definition"); var term = new SequenceParser().WithName("term"); var primary = new AlternativeParser().WithName("primary"); var exception = new UnaryParser("exception"); var factor = new SequenceParser().WithName("factor"); var meta_identifier = new RepeatParser(1).WithName("meta identifier"); var syntax_rule = new SequenceParser().WithName("syntax rule"); var rule_equals = new AlternativeParser().WithName("equals"); Parser meta_reference = meta_identifier; Parser grouped_sequence = ("(" & ows & definition_list & ows & ")").WithName("grouped sequence"); if (style.HasFlag(EbnfStyle.SquareBracketAsOptional)) { primary.Add(("[" & ows & definition_list & ows & "]").WithName("optional sequence")); } if (!style.HasFlag(EbnfStyle.CardinalityFlags)) { var repeated_sequence = ("{" & ows & definition_list & ows & "}").WithName("repeated sequence"); primary.Add(repeated_sequence); } // rules meta_identifier.Inner = meta_identifier_terminal; meta_identifier.Separator = +(Terminals.SingleLineWhiteSpace); if (!style.HasFlag(EbnfStyle.CommaSeparator)) { // w3c identifiers must be a single word meta_identifier.Maximum = 1; meta_reference = meta_reference.NotFollowedBy(ows & rule_equals); } primary.Add(grouped_sequence, meta_reference, terminal_string, special_sequence); if (style.HasFlag(EbnfStyle.CharacterSets) && !style.HasFlag(EbnfStyle.SquareBracketAsOptional)) { // w3c supports character sets primary.Add(hex_character.Named("hex character")); primary.Add(character_set); } if (style.HasFlag(EbnfStyle.NumericCardinality)) { factor.Add(~(integer & ows & "*" & ows)); } factor.Add(primary); if (style.HasFlag(EbnfStyle.CardinalityFlags)) { // w3c defines cardinality at the end of a factor var flags = style.HasFlag(EbnfStyle.SquareBracketAsOptional) ? "*+" : "?*+"; factor.Add(~(ows & Terminals.Set(flags).WithName("cardinality"))); } term.Add(factor, ~(ows & "-" & ows & exception)); exception.Inner = term; single_definition.Inner = term; single_definition.Separator = style.HasFlag(EbnfStyle.CommaSeparator) ? (Parser)(ows & "," & ows) : ows; definition_list.Inner = single_definition; definition_list.Separator = ows & "|" & ows; rule_equals.Add(style.HasFlag(EbnfStyle.DoubleColonEquals) ? "::=" : "=", ":="); syntax_rule.Add(meta_identifier, ows, rule_equals, ows, definition_list); if (style.HasFlag(EbnfStyle.SemicolonTerminator)) { syntax_rule.Add(ows, ";"); // iso rules are terminated by a semicolon } var syntax_rules = +syntax_rule; syntax_rules.Separator = style.HasFlag(EbnfStyle.SemicolonTerminator) ? ows : rws; Inner = ows & syntax_rules & ows; AttachEvents(); }
public GoldGrammar() : base("gold") { Parser oldSeparator = DefaultSeparator; // Special Terminals ExceptParser parameterCh = Terminals.Printable - Terminals.Set("\"'"); AlternativeParser nonterminalCh = Terminals.LetterOrDigit | Terminals.Set("_-. "); AlternativeParser terminalCh = Terminals.LetterOrDigit | Terminals.Set("_-."); ExceptParser literalCh = Terminals.Printable - Terminals.Set('\''); ExceptParser setLiteralCh = Terminals.Printable - Terminals.Set("[]'"); ExceptParser setNameCh = Terminals.Printable - Terminals.Set("{}"); SequenceParser parameterName = ('"' & (+parameterCh).WithName("value") & '"').Separate(); SequenceParser nonterminal = ('<' & (+nonterminalCh).WithName("value") & '>').Separate(); AlternativeParser terminal = ((+terminalCh).WithName("terminal") | ('\'' & (-literalCh).WithName("literal") & '\'')).Separate(); SequenceParser setLiteral = ('[' & +(setLiteralCh.WithName("ch") | '\'' & (-literalCh).WithName("ch") & '\'') & ']').WithName( "setLiteral"); SequenceParser setName = ('{' & (+setNameCh).WithName("value") & '}').WithName("setName"); // Line-Based Grammar Declarations var comments = new GroupParser("!*", "*!", "!"); Parser newline = Terminals.Eol; whitespace = -(Terminals.SingleLineWhiteSpace | comments); DefaultSeparator = whitespace; RepeatParser nlOpt = -newline; AlternativeParser nl = +newline | Terminals.End; // Parameter Definition AlternativeParser parameterItem = parameterName | terminal | setLiteral | setName | nonterminal; RepeatParser parameterItems = +parameterItem; SequenceParser parameterBody = parameterItems & -(nlOpt & '|' & parameterItems); parameter = (parameterName.Named("name") & nlOpt & '=' & parameterBody.WithName("body") & nl).WithName("parameter"); // Set Definition AlternativeParser setItem = setLiteral | setName; var setExp = new AlternativeParser { Name = "setExp" }; setExp.Add((setExp & nlOpt & '+' & setItem).WithName("add"), (setExp & nlOpt & '-' & setItem).WithName("sub"), setItem); setDecl = (setName & nlOpt & '=' & setExp & nl).WithName("setDecl"); // Terminal Definition var regExp2 = new SequenceParser(); OptionalParser kleeneOpt = (~((Parser)'+' | '?' | '*')).WithName("kleene"); regExpItem = ((setLiteral & kleeneOpt) | (setName & kleeneOpt) | (terminal.Named("terminal") & kleeneOpt) | ('(' & regExp2.Named("regExp2") & ')' & kleeneOpt)).WithName("regExpItem"); RepeatParser regExpSeq = (+regExpItem).WithName("regExpSeq"); regExp2.Items.Add(regExpSeq); regExp2.Items.Add(-('|' & regExpSeq)); regExp = (regExpSeq & -(nlOpt & '|' & regExpSeq)).WithName("regExp"); RepeatParser terminalName = +terminal; terminalDecl = (terminalName.Named("name") & nlOpt & '=' & regExp & nl).WithName("terminalDecl"); // Rule Definition symbol = (terminal.Named("terminal") | nonterminal.Named("nonterminal")).WithName("symbol"); handle = (-symbol).WithName("handle"); SequenceParser handles = handle & -(nlOpt & '|' & handle); ruleDecl = (nonterminal.Named("name") & nlOpt & "::=" & handles & nl).WithName("ruleDecl"); // Rules AlternativeParser definitionDecl = parameter | setDecl | terminalDecl | ruleDecl; RepeatParser content = -definitionDecl; Inner = nlOpt & content & nlOpt; DefaultSeparator = oldSeparator; AttachEvents(); }
public override bool Run(IssueManager issueManager) { /*#if DEBUG * Debugger.Launch(); #endif*/ LogDebugMessage("Repeat Processing"); try { List <IssueDto> issues = issueManager.GetRepeated(); if (issues == null || issues.Count == 0) { return(true); } List <IssueLinkType> linkTypes = issueManager.GeminiContext.Meta.LinkTypeGet(); IssueLinkType repeatedLinkType = linkTypes.Find(t => string.Compare(t.Label, "Repeated", true) == 0); if (repeatedLinkType == null && linkTypes.Count > 0) { repeatedLinkType = linkTypes[0]; } foreach (IssueDto issue in issues) { RepeatParser repeat = new RepeatParser(issue.Repeated); repeat.CurrentDateTime = DateTime.UtcNow.ToLocal(issueManager.UserContext.User.TimeZone); IssueDto lastRepeated = issueManager.GetLastCreatedIssueForOriginator(IssueOriginatorType.Repeat, issue.Id.ToString()); DateTime lastRepeatedDate = issue.Created; if (lastRepeated != null && lastRepeated.Entity.IsExisting) { lastRepeatedDate = lastRepeated.Created; } if (repeat.MaximumRepeats > 0) { List <IssueDto> repeatedIssues = issueManager.GetItemsForOriginator(IssueOriginatorType.Repeat, issue.Id.ToString()); if (repeatedIssues != null && repeatedIssues.Count >= repeat.MaximumRepeats) { continue; } } if (repeat.NeedsToRepeat(lastRepeatedDate)) { var customFields = issue.CustomFields; issue.Attachments = new List <IssueAttachmentDto>(); issue.Entity.Repeated = string.Empty; issue.Entity.OriginatorData = issue.Entity.Id.ToString(); issue.Entity.OriginatorType = IssueOriginatorType.Repeat; issue.Entity.ParentIssueId = null; issue.Entity.IsParent = false; issue.Entity.StatusId = 0; issue.Entity.ResolutionId = 0; issue.Entity.LoggedHours = 0; issue.Entity.LoggedMinutes = 0; if (issue.Entity.StartDate.HasValue && issue.Entity.DueDate.HasValue && issue.Entity.StartDate != new DateTime() && issue.Entity.DueDate != new DateTime()) { TimeSpan tsDates = issue.Entity.DueDate.Value - issue.Entity.StartDate.Value; issue.Entity.DueDate = DateTime.Today.AddDays(tsDates.TotalDays); issue.Entity.StartDate = DateTime.Today; } else { issue.Entity.StartDate = null; issue.Entity.DueDate = null; } int issueId = issue.Id; //Set the ID to 0 so it does not steal the custom fields for that tissue var originalIssueID = issue.Entity.Id; issue.Entity.Id = 0; IssueDto repeated = issueManager.Create(issue.Entity); if (customFields != null && customFields.Count > 0) { var customFieldManager = new CustomFieldManager(issueManager); foreach (var field in customFields) { try { //Find the existing ID to 'replace', if exists. var existingCF = repeated.CustomFields .SingleOrDefault(s => s.Entity.CustomFieldId == field.Entity.CustomFieldId); field.Entity.Id = existingCF == null ? 0 : existingCF.Entity.Id; field.Entity.IssueId = repeated.Entity.Id; field.Entity.ProjectId = repeated.Entity.ProjectId; customFieldManager.Update(new CustomFieldData(field.Entity)); } catch (Exception ex) { LogException(ex); } } } if (repeatedLinkType != null) { issueManager.IssueLinkCreate(repeated.Entity.Id, issueId, repeatedLinkType.Id); } } } } catch (Exception ex) { LogException(ex); } return(true); }