public string TryGetFirstSort(IListTerm term) { return term.SubTerms .Cast<IConsTerm>() .Select(t => TryGetSort(t)) .FirstOrDefault(s => s != null); }
//public bool HasNext() //{ // if (c == null) // the first call of hasNext should find the first response // Find(); // return c != null; //} //public Unifier Next() //{ // if (c == null) Find(); // Unifier b = c; // Find(); // find next response // return b; //} void Find() { while (listOutter != null && listOutter.Count != 0) { while (list.Count != 0) { IListTerm candidate = AsSyntax.AsSyntax.CreateList(list); list.Remove(list.ElementAt(list.Count - 1)); c = un.Clone(); if (c.UnifiesNoUndo(sublist, candidate)) { return; // found another sublist, c is the current response } } listOutter = listOutter.GetNext(); if (listOutter == null || listOutter.IsVar()) // the case of lists with tail { break; } list = listOutter.GetAsList(); } if (!triedEmpty) { triedEmpty = true; c = un.Clone(); if (c.UnifiesNoUndo(sublist, AsSyntax.AsSyntax.CreateList())) { return; // found another sublist, c is the current response } } c = null; // no more sublists found }
public override Literal SetAnnots(IListTerm listTerm) { annotations = null; if (listTerm == null) { return(this); } IEnumerator <IListTerm> en = listTerm.ListTermIterator(); while (en.MoveNext()) { IListTerm lt = en.Current; if (lt.GetTerm() == null) { return(this); } AddAnnot(lt.GetTerm()); if (lt.IsTail()) { annotations.SetTail(lt.GetTail()); return(this); } } return(this); }
public override Literal MakeVarsAnnon(Unifier un) { if (annotations != null) { IListTerm lt = annotations; while (!(lt.Count == 0)) { ITerm ta = lt.GetTerm(); if (ta.IsVar()) { lt.SetTerm(VarToReplace(ta, un)); } else if (ta.GetType() == typeof(Structure)) { ((Structure)ta).MakeVarsAnnon(un); } if (lt.IsTail() && lt.GetNext().IsVar()) { lt.SetNext(VarToReplace(lt.GetNext(), un)); break; } lt = lt.GetNext(); } } return(base.MakeVarsAnnon(un)); }
public void ParseListTermSimplePasses() { IListTerm lt = new ListTermImpl(new Atom("s1"), new Atom("s2")); IListTerm resultado = AsSyntax.ParseList("[bigfuckinggun]"); Assert.AreEqual(lt.ToString(), resultado.ToString()); }
public void AddErrorAnnot(ITerm t) { if (errorAnnots == null) { errorAnnots = new ListTermImpl(); } errorAnnots.Append(t); }
/// <summary> /// Reads an expression from a term. /// </summary> /// <param name="term">The term.</param> /// <returns>The expression.</returns> private IReadOnlyList<ISymbol> ReadExpression(IListTerm term) { #region Contract Contract.Requires<ArgumentNullException>(term != null); Contract.Ensures(Contract.Result<IReadOnlyList<ISymbol>>() != null); #endregion return term.SubTerms.Select(ReadSymbol).ToArray(); }
public void Dispose() { if (current != null && nextLT != null) { current.SetTerm(nextLT.GetTerm()); current.SetNext(nextLT.GetNext()); nextLT = current; } }
// Creates a plan from a list with four elements: [Literal, Trigger, Context, Body] public static new Plan NewFromListOfTerms(IListTerm lt) { ITerm c = lt[2]; if (c.IsPlanBody()) { c = ((IPlanBody)c).GetBodyTerm(); } return(new Plan(new Pred((Literal)(lt[0])), (Trigger)lt[1], (ILogicalFormula)c, (IPlanBody)lt[3])); }
public IListTerm GetErrorTerms() { IListTerm e = CreateBasicErrorAnnots(error, Message); if (errorAnnots != null) { e.Concat(errorAnnots.CloneLT()); } return(e); }
public override object Execute(Reasoner ts, Unifier un, ITerm[] args) { CheckArguments(args); Trigger te = null; try { te = Trigger.TryToGetTrigger(args[0]); } catch (ParseException e) {} if (te == null) { throw JasonityException.CreateWrongArgument(this, "first argument '" + args[0] + "' must follow the syntax of a trigger."); } IListTerm labels = new ListTermImpl(); IListTerm lt = new ListTermImpl(); IListTerm last = lt; if (!te.GetLiteral().HasSource()) { // the ts.relevantPlans requires a source to work properly te.SetLiteral(te.GetLiteral().ForceFullLiteralImpl()); te.GetLiteral().AddSource(new UnnamedVar()); } List <Option> rp = ts.RelevantPlans(te); if (rp != null) { foreach (Option opt in rp) { // remove sources (this IA is used for communication) Plan np = (Plan)opt.GetPlan().Clone(); if (np.GetLabel() != null) { np.GetLabel().DelSources(); } np.SetAsPlanTerm(true); np.MakeVarsAnnon(); last = last.Append(np); if (args.Length == 3) { labels.Add(np.GetLabel()); } } } bool ok = un.Unifies(lt, args[1]); // args[1] is a var; if (ok && args.Length == 3) { ok = un.Unifies(labels, args[2]); } return(ok); }
public Pred(Atom namespce, Literal l) : base(namespce, l) { if (l.HasAnnot()) { annotations = l.GetAnnots().CloneLT(); } else { annotations = null; } }
private IStringTerm Concat(ITermFactory factory, IListTerm <IStringTerm> strs) { var sb = new StringBuilder(strs.Sum(s => s.Value.Length)); foreach (var s in strs) { sb.Append(s.Value); } return(factory.String(sb.ToString())); }
public static IListTerm ParseList(string sList) { as2j parser = new as2j(new StringReader(sList)); IListTerm l = parser.List(); if (parser.getNextToken().kind != as2jConstants.EOF) { throw new ParseException("Expected <EOF> after " + l + " for parameter '" + sList + "'"); } return(l); }
public SubListStdLibIterator(Reasoner ts, Unifier un, ITerm[] args, ITerm sublist) { this.ts = ts; this.un = un; this.args = args; this.sublist = sublist; this.c = null; listOutter = (IListTerm)args[1]; list = listOutter.GetAsList(); triedEmpty = false; }
public static IListTerm CreateList(List <ITerm> terms) { IListTerm l = new ListTermImpl(); IListTerm tail = l; foreach (ITerm t in terms) { tail = tail.Append((ITerm)t.Clone()); // Como uso el Clone de C# lo que clono son object que luego hay que castear... } return(l); }
// copy the set to a new list private IListTerm SetToList(ISet <ITerm> set) { IListTerm result = new ListTermImpl(); IListTerm tail = result; foreach (ITerm t in set) { tail = tail.Append((ITerm)t.Clone()); // Como uso el Clone de C# lo que clono son object que luego hay que castear... } return(result); }
public static IListTerm CreateList(params ITerm[] terms) { IListTerm l = new ListTermImpl(); IListTerm tail = l; foreach (ITerm t in terms) { tail = tail.Append(t); } return(l); }
public Pred(Literal l, Unifier u) : base(l, u) { if (l.HasAnnot()) { SetAnnots((IListTerm)l.GetAnnots().CApply(u)); } else { annotations = null; } }
public override object Execute(Reasoner ts, Unifier un, ITerm[] args) { CheckArguments(args); IRuntimeServices rs = ts.GetUserAgArch().GetRuntimeServices(); IListTerm ln = new ListTermImpl(); IListTerm tail = ln; foreach (string a in rs.GetAgentsNames()) { tail = tail.Append(new Atom(a)); } return(un.Unifies(args[0], ln)); }
/// <summary> /// Initializes a new instance of the <see cref="ListTerm"/> class, /// that represents a non-empty list. /// </summary> /// <param name="head">The head of the list.</param> /// <param name="tail">The tail of the list.</param> /// <param name="annotations">The annotations of the term.</param> public ListTerm(ITerm head, IListTerm tail, IReadOnlyCollection<ITerm> annotations) : base(annotations) { #region Contract Contract.Requires<ArgumentNullException>(head != null); Contract.Requires<ArgumentNullException>(tail != null); Contract.Requires<ArgumentNullException>(annotations != null); Contract.Requires<ArgumentException>(Contract.ForAll(annotations, a => a != null)); #endregion this.Head = head; this.Tail = tail; this.Count = tail.Count + 1; }
public override object Execute(Reasoner reasoner, Unifier un, ITerm[] args) { CheckArguments(args); ITerm var = args[0]; ILogicalFormula logExpr = (ILogicalFormula)args[1]; IListTerm all = new ListTermImpl(); IListTerm tail = all; IEnumerator <Unifier> iu = logExpr.LogicalConsequence(reasoner.GetAgent(), un); while (iu.MoveNext()) { tail = tail.Append(var.CApply(iu.Current)); } return(un.Unifies(args[2], all)); }
/// <summary> /// Builds a new list term. /// </summary> /// <param name="head">The head of the list.</param> /// <param name="tail">The tail of the list.</param> /// <returns>The list term.</returns> public IListTerm ListConsNil(ITerm head, IListTerm tail) { #region Contract if (head == null) { throw new ArgumentNullException(nameof(head)); } if (tail == null) { throw new ArgumentNullException(nameof(tail)); } #endregion return(ListConsNil(head, tail, Terms.Empty)); }
IListTerm DeleteFromList(int index, int end, IListTerm l) { IListTerm r = new ListTermImpl(); IListTerm last = r; int i = 0; foreach (ITerm t in l) { if (i < index || i >= end) { last = last.Append((ITerm)t.Clone()); // Como uso el Clone de C# lo que clono son object que luego hay que castear... } i++; } return(r); }
//public bool HasNext() //{ // if (c == null) // the first call of hasNext should find the first response // Find(); // return c != null; //} //public Unifier Next() //{ // if (c == null) // Find(); // Unifier b = c; // Find(); // find next response // return b; //} void Find() { while (list.MoveNext()) { IListTerm l = list.Current; if (l.IsVar()) // the case of the tail of the list { break; } c = un.Clone(); if (c.UnifiesNoUndo(sublist, AsSyntax.AsSyntax.CreateList(l))) { return; // found another sublist, c is the current response } } c = null; // no more sublists found }
public override object Execute(Reasoner ts, Unifier un, ITerm[] args) { CheckArguments(args); ITerm l1 = args[0]; if (l1.IsList()) { IListTerm lt = l1 as IListTerm; return(lt.Count == 0); } else if (l1.IsString()) { IStringTerm st = l1 as IStringTerm; return(st.GetString().Length == 0); } return(false); }
/// <summary> /// Initializes a new instance of the <see cref="ModuleATerm"/> class. /// </summary> /// <param name="factory">The factory that created this term.</param> /// <param name="name">The name.</param> /// <param name="definitions">The definitions.</param> /// <param name="annotations">The annotations of the term.</param> public ModuleATerm(ITermFactory factory, IStringTerm name, IListTerm <IEntityTerm> definitions, IReadOnlyCollection <ITerm> annotations) : base(factory, annotations) { #region Contract if (name == null) { throw new ArgumentNullException(nameof(name)); } if (definitions == null) { throw new ArgumentNullException(nameof(definitions)); } #endregion this.Name = name; this.Definitions = definitions; this.subterms = new SubtermCollection(this); }
/// <summary> /// Initializes a new instance of the <see cref="EntityATerm"/> class. /// </summary> /// <param name="factory">The factory that created this term.</param> /// <param name="name">The name.</param> /// <param name="properties">The properties.</param> /// <param name="annotations">The annotations of the term.</param> public EntityATerm(ITermFactory factory, IStringTerm name, IListTerm <IPropertyTerm> properties, IReadOnlyCollection <ITerm> annotations) : base(factory, annotations) { #region Contract if (name == null) { throw new ArgumentNullException(nameof(name)); } if (properties == null) { throw new ArgumentNullException(nameof(properties)); } #endregion this.Name = name; this.Properties = properties; this.subterms = new SubtermCollection(this); }
/// <inheritdoc /> protected override void WriteListTerm(IListTerm term, TextWriter writer) { #region Contract if (term == null) { throw new ArgumentNullException(nameof(term)); } if (writer == null) { throw new ArgumentNullException(nameof(writer)); } #endregion writer.Write('['); this.WriteTermsList(term.SubTerms, ",", writer); writer.Write(']'); this.WriteAnnotations(term.Annotations, writer); }
/// <inheritdoc /> public override IListTerm ListConsNil(ITerm head, IListTerm tail, IReadOnlyCollection <ITerm> annotations) { #region Contract if (head == null) { throw new ArgumentNullException(nameof(head)); } if (tail == null) { throw new ArgumentNullException(nameof(tail)); } if (annotations == null) { throw new ArgumentNullException(nameof(annotations)); } #endregion return(new ListTerm(head, tail, annotations)); }
IListTerm DeleteFromList(ITerm element, IListTerm l, Unifier un) { Unifier bak = un; IListTerm r = new ListTermImpl(); IListTerm last = r; foreach (ITerm t in l) { if (un.Unifies(element, t)) { un = bak.Clone(); } else { last = last.Append((ITerm)t.Clone()); // Como uso el Clone de C# lo que clono son object que luego hay que castear... } } return(r); }
public override object Execute(Reasoner ts, Unifier un, ITerm[] args) { if (args[0].IsList()) { if (!args[args.Length - 1].IsVar() && !args[args.Length - 1].IsList()) { throw new JasonityException("Last argument of concat '" + args[args.Length - 1] + "'is not a list nor a variable."); } IListTerm result = args[0].Clone() as IListTerm; for (int i = 1; i < args.Length - 1; i++) { if (!args[i].IsList()) { throw JasonityException.CreateWrongArgument(this, "arg[" + i + "] is not a list"); } result.Concat((IListTerm)args[i].Clone()); } return(un.Unifies(result, args[args.Length - 1])); } else { if (!args[args.Length - 1].IsVar() && !args[args.Length - 1].IsString()) { throw JasonityException.CreateWrongArgument(this, "Last argument '" + args[args.Length - 1] + "' is not a string nor a variable."); } string vl = args[0].ToString(); if (args[0].IsString()) { vl = ((IStringTerm)args[0]).GetString(); } StringBuilder sr = new StringBuilder(vl); for (int i = 0; i < args.Length - 1; i++) { vl = args[i].ToString(); if (args[i].IsString()) { vl = ((IStringTerm)args[i]).GetString(); } sr.Append(vl); } return(un.Unifies(new StringTermImpl(sr.ToString()), args[args.Length - 1])); } }
public ITerm GetAsTerm() { IListTerm lf = new ListTermImpl(); IListTerm tail = lf; foreach (VarTerm k in function.Keys) { ITerm vl; function.TryGetValue(k, out vl); vl.Clone(); // Como uso el Clone de C# lo que clono son object que luego hay que castear... if (vl is Literal) { ((Literal)vl).MakeVarsAnnon(); } // Variable must be changed to avoid cyclic references later Structure pair = AsSyntax.AsSyntax.CreateStructure("dictionary", UnnamedVar.Create(k.ToString()), vl); tail = tail.Append(pair); } return(lf); }
/// <summary> /// Parses the states from the parse table. /// </summary> /// <param name="listTerm">A list of state terms.</param> /// <param name="labels">The labels in the parse table.</param> /// <returns>The parsed states.</returns> /// <example> /// A state term might look like this: /// <code> /// state-rec(0,[goto([47],22)],[action([256],[reduce(0,280,0)])]) /// </code> /// </example> private IReadOnlyList<State> ParseStates(IListTerm listTerm, IReadOnlyList<Label> labels) { #region Contract Contract.Requires<ArgumentNullException>(listTerm != null); Contract.Requires<ArgumentNullException>(labels != null); Contract.Ensures(Contract.Result<IReadOnlyList<State>>() != null); #endregion // NOTE: We assume that all state indices are less than the number of states. var result = new State[listTerm.Count]; foreach (var term in from t in listTerm.SubTerms select t.ToCons("state-rec", 3)) { int stateIndex = term[0].ToInt32(); var gotos = ParseGotos((IListTerm)term[1]); var actions = ParseActions((IListTerm)term[2], labels); result[stateIndex] = new State(gotos, actions); } return result; }
/// <summary> /// Parses the labels from the parse table. /// </summary> /// <param name="listTerm">A list of label terms.</param> /// <returns>The parsed labels.</returns> /// <example> /// A label term might look like this: /// <code> /// label(prod([lit("\""),lex(iter-star(sort("StringChar"))),lit("\"")],lex(sort("STRING")),no-attrs),378) /// </code> /// </example> private IReadOnlyList<Label> ParseLabels(IListTerm listTerm) { #region Contract Contract.Requires<ArgumentNullException>(listTerm != null); Contract.Ensures(Contract.Result<IReadOnlyList<Label>>() != null); #endregion // NOTE: We assume that all label indices are less than the number of labels + 255. var result = new Label[listTerm.Count]; foreach (var term in from t in listTerm.SubTerms select t.ToCons("label", 2)) { // NOTE: Labels and characters are indexed at the same time. Below 256 it denotes // a character literal, above 255 it denotes a label with a production. // Therefore, we have to subtract 255 since we're dealing with labels separately. int labelIndex = term[1].ToInt32() - SpoofaxParseTableFormat.LabelBase; var productionTerm = term[0].ToCons("prod", 3); var production = this.productionFormat.Read(productionTerm); result[labelIndex] = new Label(production); } return result; }
/// <summary> /// Parses the gotos from the parse table. /// </summary> /// <param name="listTerm">A list of goto terms.</param> /// <returns>The parsed gotos.</returns> /// <example> /// A goto term might look like this: /// <code> /// goto([range(9,10),13,32],21) /// </code> /// </example> private IReadOnlyList<Goto> ParseGotos(IListTerm listTerm) { #region Contract Contract.Requires<ArgumentNullException>(listTerm != null); Contract.Ensures(Contract.Result<IReadOnlyList<Goto>>() != null); #endregion var result = new Goto[listTerm.Count]; int index = 0; foreach (var term in from t in listTerm.SubTerms select t.ToCons("goto", 2)) { var characters = ParseCharacterRanges((IListTerm)term[0]); var labels = ParseLabelRanges((IListTerm)term[0]); var nextState = new StateRef(term[1].ToInt32()); result[index++] = new Goto(nextState, characters, labels); } return result; }
/// <summary> /// Parses the actions from the parse table. /// </summary> /// <param name="listTerm">A list of action terms.</param> /// <param name="labels">The labels in the parse table.</param> /// <returns>The parsed actions.</returns> /// <example> /// An action term might look like this: /// <code> /// action([47],[shift(22),reduce(0,280,0,[follow-restriction([char-class([42,47])])])]) /// </code> /// </example> private IEnumerable<Action> ParseActions(IListTerm listTerm, IReadOnlyList<Label> labels) { #region Contract Contract.Requires<ArgumentNullException>(listTerm != null); Contract.Requires<ArgumentNullException>(labels != null); Contract.Ensures(Contract.Result<IEnumerable<Action>>() != null); #endregion var result = new Action[listTerm.Count]; int index = 0; foreach (var term in from t in listTerm.SubTerms select t.ToCons("action", 2)) { var characters = ParseCharacterRanges((IListTerm)term[0]); var actionItems = ParseActionItems((IListTerm)term[1], labels); result[index++] = new Action(characters, actionItems); } return result; }
/// <summary> /// Parses the priorities items from the parse table. /// </summary> /// <param name="listTerm">A list of priority terms.</param> /// <returns>The parsed priorities.</returns> /// <example> /// The term might look like this: /// <code> /// [arg-gtr-prio(286,2,286), gtr-prio(301,295)] /// </code> /// </example> private IReadOnlyList<Priority> ParsePriorities(IListTerm listTerm) { #region Contract Contract.Requires<ArgumentNullException>(listTerm != null); Contract.Ensures(Contract.Result<IReadOnlyList<Priority>>() != null); #endregion var result = new List<Priority>(listTerm.Count); foreach (var term in listTerm.SubTerms.Cast<IConsTerm>()) { switch (term.Name) { case "left-prio": case "right-prio": case "non-assoc": // Not supported. break; case "gtr-prio": { var left = new LabelRef(term[0].ToInt32() - SpoofaxParseTableFormat.LabelBase); var right = new LabelRef(term[1].ToInt32() - SpoofaxParseTableFormat.LabelBase); if (left != right) result.Add(new Priority(left, right, PriorityType.Greater)); break; } case "arg-gtr-prio": { var left = new LabelRef(term[0].ToInt32() - SpoofaxParseTableFormat.LabelBase); var arg = term[1].ToInt32(); var right = new LabelRef(term[2].ToInt32() - SpoofaxParseTableFormat.LabelBase); if (left != right) result.Add(new Priority(left, right, arg, PriorityType.Greater)); break; } default: throw new InvalidParseTableException("Unknown priority: " + term); } } return result; }
/// <inheritdoc /> protected override void WriteListTerm(IListTerm term, TextWriter writer) { // CONTRACT: Inherited from TermTextWriter writer.Write('['); this.WriteTermsList(term.SubTerms, ",", writer); writer.Write(']'); this.WriteAnnotations(term.Annotations, writer); }
/// <summary> /// Reads a character set from a list term. /// </summary> /// <param name="listTerm">A list of characters and character ranges.</param> /// <returns>The read character set.</returns> /// <example> /// The list term might look like this: /// <code> /// [range(9,10),13,32] /// </code> /// </example> private IReadOnlySet<CodePoint> ReadCharacterRanges(IListTerm listTerm) { #region Contract Contract.Requires<ArgumentNullException>(listTerm != null); Contract.Ensures(Contract.Result<IReadOnlySet<CodePoint>>() != null); #endregion CodePointSet characters = new CodePointSet(); foreach (var term in listTerm.SubTerms) { int? charValue = term.AsInt32(); IConsTerm rangeTerm = term.AsCons("range", 2); if (charValue != null) { characters.Add(new CodePoint((int)charValue)); } else if (rangeTerm != null) { int start = rangeTerm[0].ToInt32(); int end = rangeTerm[1].ToInt32(); characters.AddRange(new CodePoint(start), new CodePoint(end)); } else throw new InvalidOperationException("Unrecognized term: " + term); } // If the range contains the 8-bit Eof, change it into the 16-bit Eof. if (characters.Contains(new CodePoint(256))) { characters.Remove(new CodePoint(256)); characters.Add(CodePoint.Eof); } return characters; }
public void VisitList(IListTerm term) { Contract.Requires<ArgumentNullException>(term != null); }
protected override void WriteListTerm(IListTerm term, TextWriter writer) { Contract.Requires(term != null); Contract.Requires(writer != null); }
/// <summary> /// Parses a set of labels from the parse table. /// </summary> /// <param name="listTerm">A list of label indices and label index ranges.</param> /// <returns>The parsed labels set.</returns> /// <example> /// The list term might look like this: /// <code> /// [range(309,310),313,332] /// </code> /// </example> private IEnumerable<LabelRef> ParseLabelRanges(IListTerm listTerm) { #region Contract Contract.Requires<ArgumentNullException>(listTerm != null); Contract.Ensures(Contract.Result<IEnumerable<LabelRef>>() != null); #endregion // NOTE: Labels have index 256 or higher, so we subtract 256 (LabelOffset). var labels = new List<LabelRef>(); foreach (var term in listTerm.SubTerms) { int? labelIndex = term.AsInt32(); IConsTerm rangeTerm = term.AsCons("range", 2); if (labelIndex != null) { if (labelIndex >= SpoofaxParseTableFormat.LabelBase) labels.Add(new LabelRef(((int)labelIndex) - SpoofaxParseTableFormat.LabelBase)); // Else: ignore. It's a character which we'll add later. } else if (rangeTerm != null) { // Clip the start to the min label index we read. int start = Math.Max(SpoofaxParseTableFormat.LabelBase, rangeTerm[0].ToInt32()); int end = rangeTerm[1].ToInt32(); if (end >= SpoofaxParseTableFormat.LabelBase) { for (int i = start - SpoofaxParseTableFormat.LabelBase; i <= end - SpoofaxParseTableFormat.LabelBase; i++) { labels.Add(new LabelRef(i)); } } // Else: ignore. It's a range of characters which we'll add later. } else throw new InvalidOperationException("Unrecognized term: " + term); } return labels; }
/// <summary> /// Parses a character set from the parse table. /// </summary> /// <param name="listTerm">A list of characters and character ranges.</param> /// <returns>The parsed character set.</returns> /// <example> /// The list term might look like this: /// <code> /// [range(9,10),13,32] /// </code> /// </example> private IReadOnlySet<CodePoint> ParseCharacterRanges(IListTerm listTerm) { #region Contract Contract.Requires<ArgumentNullException>(listTerm != null); Contract.Ensures(Contract.Result<IReadOnlySet<CodePoint>>() != null); #endregion CodePointSet characters = new CodePointSet(); foreach (var term in listTerm.SubTerms) { int? charValue = term.AsInt32(); IConsTerm rangeTerm = term.AsCons("range", 2); if (charValue != null) { if (charValue <= SpoofaxParseTableFormat.CharacterMax) characters.Add(new CodePoint((int)charValue)); // Else: ignore. It's a label which we'll add later. } else if (rangeTerm != null) { int start = rangeTerm[0].ToInt32(); // Clip the end to the max character we read. int end = Math.Min(rangeTerm[1].ToInt32(), SpoofaxParseTableFormat.CharacterMax); if (start <= SpoofaxParseTableFormat.CharacterMax) characters.AddRange(new CodePoint(start), new CodePoint(end)); // Else: ignore. It's a range of labels which we'll add later. } else throw new InvalidParseTableException("Unrecognized term: " + term); } // If the range contains the 8-bit Eof, change it into the 16-bit Eof. if (characters.Contains(new CodePoint(256))) { characters.Remove(new CodePoint(256)); characters.Add(CodePoint.Eof); } return characters; }
/// <summary> /// Writes a list term to the specified writer. /// </summary> /// <param name="term">The term to write.</param> /// <param name="writer">The text writer to write to.</param> protected abstract void WriteListTerm(IListTerm term, TextWriter writer);
public override IListTerm ListConsNil(ITerm head, IListTerm tail, IReadOnlyCollection<ITerm> annotations) { Contract.Requires<ArgumentNullException>(head != null); Contract.Requires<ArgumentNullException>(tail != null); Contract.Requires<ArgumentNullException>(annotations != null); return default(IListTerm); }
/// <summary> /// Builds a new list term. /// </summary> /// <param name="head">The head of the list.</param> /// <param name="tail">The tail of the list.</param> /// <param name="annotations">A set of annotations for the term.</param> /// <returns>The list term.</returns> public abstract IListTerm ListConsNil(ITerm head, IListTerm tail, IReadOnlyCollection<ITerm> annotations);
/// <summary> /// Parses a list of lookahead character ranges. /// </summary> /// <param name="listTerm">The list term.</param> /// <returns>The parse character ranges.</returns> /// <example> /// The term might look like this: /// <code> /// [follow-restriction([char-class([42,47])])] /// </code> /// </example> private IReadOnlyList<IReadOnlySet<CodePoint>> ParseLookaheadCharRanges(IListTerm listTerm) { #region Contract Contract.Requires<ArgumentNullException>(listTerm != null); Contract.Ensures(Contract.Result<IReadOnlyList<IReadOnlySet<CodePoint>>>() != null); #endregion var result = new List<IReadOnlySet<CodePoint>>(listTerm.Count); foreach (var term in listTerm.SubTerms) { IListTerm l, n; if (term.IsCons("look", 2)) // sdf2bundle 2.4 { l = (IListTerm)term[0][0]; n = (IListTerm)term[1]; } else if (term.IsCons("follow-restriction", 1)) // sdf2bundle 2.6 { l = (IListTerm)term[0][0].ToCons("char-class", 1)[0]; n = ((IListTerm)term[0]).Tail; } else throw new InvalidParseTableException("Unknown term: " + term); result.Add(ParseCharacterRanges(l)); // FIXME: multiple lookahead are not fully supported or tested // (and should work for both 2.4 and 2.6 tables) if (n.SubTerms.Count > 0) throw new InvalidParseTableException("Multiple lookahead not fully supported."); foreach(var nt in n.SubTerms) { result.Add(ParseCharacterRanges((IListTerm)nt[0])); } } return result; }
/// <inheritdoc /> public override IListTerm ListConsNil(ITerm head, IListTerm tail, IReadOnlyCollection<ITerm> annotations) { // CONTRACT: Inherited from TermFactory return new ListTerm(head, tail, annotations); }
/// <summary> /// Builds a new list term. /// </summary> /// <param name="head">The head of the list.</param> /// <param name="tail">The tail of the list.</param> /// <returns>The list term.</returns> public IListTerm ListConsNil(ITerm head, IListTerm tail) { #region Contract Contract.Requires<ArgumentNullException>(head != null); Contract.Requires<ArgumentNullException>(tail != null); Contract.Ensures(Contract.Result<IListTerm>() != null); #endregion return ListConsNil(head, tail, TermFactory.EmptyTermList); }
/// <summary> /// Parses the action items from the parse table. /// </summary> /// <param name="listTerm">A list of action item terms.</param> /// <param name="labels">The labels in the parse table.</param> /// <returns>The parsed action items.</returns> /// <example> /// The list term might look like this: /// <code> /// [shift(22),reduce(0,280,0,[follow-restriction([char-class([42,47])])])] /// </code> /// </example> private IEnumerable<ActionItem> ParseActionItems(IListTerm listTerm, IReadOnlyList<Label> labels) { #region Contract Contract.Requires<ArgumentNullException>(listTerm != null); Contract.Requires<ArgumentNullException>(labels != null); Contract.Ensures(Contract.Result<IEnumerable<ActionItem>>() != null); #endregion var result = new ActionItem[listTerm.Count]; int index = 0; foreach (var term in listTerm.SubTerms) { ActionItem actionItem; if (term.IsCons("accept", 0)) actionItem = ParseAccept((IConsTerm)term); else if (term.IsCons("shift", 1)) actionItem = ParseShift((IConsTerm)term); else if (term.IsCons("reduce", 3)) actionItem = ParseReduce((IConsTerm)term, labels); else if (term.IsCons("reduce", 4)) actionItem = ParseReduce((IConsTerm)term, labels); else throw new InvalidParseTableException("Unrecognized term: " + term); result[index++] = actionItem; } return result; }