Free cookie consent management tool by TermsFeed Policy Generator

source: branches/HeuristicLab.Problems.GPDL/HeuristicLab.Grammars/3.3/Grammar.cs @ 10067

Last change on this file since 10067 was 10067, checked in by gkronber, 9 years ago

#2026 worked on brute force solver for GPDL problems.

File size: 4.4 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2013 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
4 *
5 * This file is part of HeuristicLab.
6 *
7 * HeuristicLab is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation, either version 3 of the License, or
10 * (at your option) any later version.
11 *
12 * HeuristicLab is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
19 */
20#endregion
21
22using System;
23using System.Collections.Generic;
24using System.Diagnostics;
25using System.Linq;
26using System.Text.RegularExpressions;
27
28namespace HeuristicLab.Grammars {
29  public class Grammar : IGrammar {
30    public static readonly ISymbol EmptySymbol = new Symbol("EPS");
31    private Dictionary<ISymbol, List<Sequence>> rules = new Dictionary<ISymbol, List<Sequence>>();
32    private HashSet<ISymbol> allSymbols = new HashSet<ISymbol>();
33
34    public ISymbol StartSymbol { get; set; }
35    public IEnumerable<ISymbol> TerminalSymbols { get { return allSymbols.Except(NonTerminalSymbols); } }
36    public IEnumerable<ISymbol> NonTerminalSymbols { get { return rules.Keys; } }
37    public IEnumerable<ISymbol> Symbols { get { return allSymbols; } }
38
39    public Grammar(ISymbol startSymbol) {
40      Debug.Assert(startSymbol != EmptySymbol);
41      this.StartSymbol = startSymbol;
42    }
43
44    public int NumberOfAlternatives(ISymbol ntSymbol) {
45      return rules[ntSymbol].Count;
46    }
47
48    public IEnumerable<Sequence> GetAlternatives(ISymbol ntSymbol) {
49      return rules[ntSymbol].AsReadOnly();
50    }
51
52    public Sequence GetAlternative(ISymbol ntSymbol, int index) {
53      return rules[ntSymbol][index];
54    }
55
56    public virtual void AddProductionRule(ISymbol ntSymbol, Sequence production) {
57      Debug.Assert(ntSymbol != EmptySymbol);
58
59      List<Sequence> l;
60      if (!rules.TryGetValue(ntSymbol, out l)) {
61        l = new List<Sequence>();
62        rules.Add(ntSymbol, l);
63
64        allSymbols.Add(ntSymbol); // register new nt-symbol
65      }
66      // check if the same production exists already
67      Debug.Assert(!l.Any(s => s.SequenceEqual(production)));
68
69      l.Add(production);
70
71      foreach (var s in production) allSymbols.Add(s); // register all symbols in the production
72    }
73
74    public bool IsTerminal(ISymbol symbol) {
75      return !rules.ContainsKey(symbol) && allSymbols.Contains(symbol);
76    }
77    public bool IsNonTerminal(ISymbol symbol) {
78      return rules.ContainsKey(symbol);
79    }
80
81    // checks if a rule exists for each NT symbol
82    public bool IsComplete() {
83      return rules.ContainsKey(StartSymbol) &&
84             NonTerminalSymbols.All(nt => rules.ContainsKey(nt));
85    }
86
87    private static Regex ruleExpr = new Regex(@"\s*(?<ntSymbol>\w+)\s*->\s*(?<alternative>\w+(?:\s+\w+)*)(?:\s*\|\s*(?<alternative>\w+(?:\s+\w+)*))*");
88    private static Regex empty = new Regex(@"^\s*$");
89    public static Grammar FromString(string gStr) {
90      var lines = gStr.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
91      lines = lines.Where(l => !empty.IsMatch(l)).ToArray(); // remove empty lines
92
93      // first line is the rule for the start-symbol
94      var m = ruleExpr.Match(lines.First());
95      var startSymbol = new Symbol(m.Groups["ntSymbol"].Value);
96      var g = new Grammar(startSymbol);
97      foreach (var alt in m.Groups["alternative"].Captures) {
98        g.AddProductionRule(startSymbol, new Sequence(alt.ToString().Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).Select(n => new Symbol(n)).ToList<ISymbol>()));
99      }
100      foreach (var line in lines.Skip(1)) {
101        m = ruleExpr.Match(line);
102        var ntSymbol = new Symbol(m.Groups["ntSymbol"].Value);
103        foreach (var alt in m.Groups["alternative"].Captures) {
104          g.AddProductionRule(ntSymbol, new Sequence(alt.ToString().Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).Select(n => new Symbol(n)).ToList<ISymbol>()));
105        }
106      }
107
108      return g;
109    }
110  }
111}
Note: See TracBrowser for help on using the repository browser.