[10062] | 1 | using System;
|
---|
| 2 | using System.Collections.Generic;
|
---|
[10067] | 3 | using System.Diagnostics;
|
---|
[10062] | 4 | using System.Linq;
|
---|
[10335] | 5 | using System.Text;
|
---|
[10067] | 6 | using HeuristicLab.Grammars;
|
---|
[10062] | 7 |
|
---|
| 8 | namespace CodeGenerator {
|
---|
[10080] | 9 | public class RandomSearchCodeGen {
|
---|
[10062] | 10 |
|
---|
| 11 | private string solverTemplate = @"
|
---|
| 12 | namespace ?PROBLEMNAME? {
|
---|
| 13 | public sealed class ?IDENT?Solver {
|
---|
[10100] | 14 | private static double baseTerminalProbability = 0.05; // 5% of all samples are only a terminal node
|
---|
| 15 | private static double terminalProbabilityInc = 0.05; // for each level the probability to sample a terminal grows by 5%
|
---|
[10335] | 16 |
|
---|
| 17 | private static Dictionary<int, int[]> transition = new Dictionary<int, int[]>() {
|
---|
| 18 | ?TRANSITIONTABLE?
|
---|
| 19 | };
|
---|
| 20 | private static Dictionary<int, int> subtreeCount = new Dictionary<int, int>() {
|
---|
| 21 | { -1, 0 }, // terminals
|
---|
| 22 | ?SUBTREECOUNTTABLE?
|
---|
| 23 | };
|
---|
| 24 | private static string[] symb = new string[] { ?SYMBOLNAMES? };
|
---|
| 25 |
|
---|
[10100] | 26 |
|
---|
| 27 | public sealed class SolverState : ISolverState {
|
---|
| 28 | private class Tree {
|
---|
| 29 | public int altIdx;
|
---|
| 30 | // public string symbol; // for debugging
|
---|
| 31 | public List<Tree> subtrees;
|
---|
| 32 | public Tree(int state, int altIdx) {
|
---|
| 33 | subtrees = new List<Tree>(subtreeCount[state]);
|
---|
| 34 | this.altIdx = altIdx;
|
---|
| 35 | }
|
---|
| 36 | }
|
---|
[10335] | 37 |
|
---|
| 38 | ?TERMINALNODEDEFINITIONS?
|
---|
| 39 |
|
---|
[10100] | 40 | public int curDepth;
|
---|
| 41 | public int steps;
|
---|
[10086] | 42 | public int depth;
|
---|
[10100] | 43 | private readonly Stack<Tree> nodes;
|
---|
[10335] | 44 | private readonly ?IDENT?Problem problem;
|
---|
[10100] | 45 |
|
---|
[10335] | 46 | public SolverState(?IDENT?Problem problem, int seed) {
|
---|
[10100] | 47 | this.problem = problem;
|
---|
| 48 | this.nodes = new Stack<Tree>();
|
---|
| 49 |
|
---|
| 50 | // create a random tree
|
---|
| 51 | var tree = SampleTree(new Random(seed), 0, -1); // state 0 is the state for the start symbol
|
---|
| 52 | nodes.Push(tree);
|
---|
[10086] | 53 | }
|
---|
[10062] | 54 |
|
---|
[10100] | 55 | public void Reset() {
|
---|
| 56 | // stack must contain only the root of the tree
|
---|
| 57 | System.Diagnostics.Debug.Assert(nodes.Count == 1);
|
---|
[10086] | 58 | }
|
---|
[10100] | 59 |
|
---|
| 60 | private Tree SampleTree(Random random, int state, int altIdx) {
|
---|
| 61 | // Console.Write(state + "" "");
|
---|
| 62 | curDepth += 1;
|
---|
| 63 | steps += 1;
|
---|
| 64 | depth = Math.Max(depth, curDepth);
|
---|
| 65 | var t = new Tree(state, altIdx);
|
---|
[10335] | 66 |
|
---|
[10100] | 67 | // t.symbol = symb.Length > state ? symb[state] : ""TERM"";
|
---|
| 68 | // if the symbol has alternatives then we must choose one randomly (only one sub-tree in this case)
|
---|
| 69 | if(subtreeCount[state] == 1) {
|
---|
| 70 | var targetStates = transition[state];
|
---|
| 71 | var i = SampleAlternative(random, state);
|
---|
| 72 | if(targetStates.Length == 0) {
|
---|
| 73 | //terminal
|
---|
| 74 | t.subtrees.Add(SampleTree(random, -1, i));
|
---|
| 75 | } else {
|
---|
| 76 | t.subtrees.Add(SampleTree(random, targetStates[i], i));
|
---|
| 77 | }
|
---|
| 78 | } else {
|
---|
| 79 | // if the symbol contains only one sequence we must use create sub-trees for each symbol in the sequence
|
---|
| 80 | for(int i = 0; i < subtreeCount[state]; i++) {
|
---|
| 81 | t.subtrees.Add(SampleTree(random, transition[state][i], i));
|
---|
| 82 | }
|
---|
| 83 | }
|
---|
| 84 | curDepth -=1;
|
---|
| 85 | return t;
|
---|
[10086] | 86 | }
|
---|
[10100] | 87 |
|
---|
| 88 | public int PeekNextAlternative() {
|
---|
| 89 | // this must only be called nodes that contain alternatives and therefore must only have single-symbols alternatives
|
---|
| 90 | System.Diagnostics.Debug.Assert(nodes.Peek().subtrees.Count == 1);
|
---|
| 91 | return nodes.Peek().subtrees[0].altIdx;
|
---|
| 92 | }
|
---|
| 93 |
|
---|
| 94 | public void Follow(int idx) {
|
---|
| 95 | nodes.Push(nodes.Peek().subtrees[idx]);
|
---|
| 96 | }
|
---|
| 97 |
|
---|
| 98 | public void Unwind() {
|
---|
| 99 | nodes.Pop();
|
---|
| 100 | }
|
---|
| 101 |
|
---|
| 102 | private int SampleAlternative(Random random, int state) {
|
---|
| 103 | switch(state) {
|
---|
| 104 |
|
---|
| 105 | ?SAMPLEALTERNATIVECODE?
|
---|
| 106 |
|
---|
| 107 | default: throw new InvalidOperationException();
|
---|
| 108 | }
|
---|
| 109 | }
|
---|
| 110 |
|
---|
| 111 | private double TerminalProbForDepth(int depth) {
|
---|
| 112 | return baseTerminalProbability + depth * terminalProbabilityInc;
|
---|
| 113 | }
|
---|
[10086] | 114 | }
|
---|
| 115 |
|
---|
[10062] | 116 | public static void Main(string[] args) {
|
---|
[10100] | 117 | if(args.Length >= 1) ParseArguments(args);
|
---|
| 118 |
|
---|
| 119 | var problem = new ?IDENT?Problem();
|
---|
| 120 | var solver = new ?IDENT?Solver(problem);
|
---|
[10062] | 121 | solver.Start();
|
---|
| 122 | }
|
---|
[10100] | 123 | private static void ParseArguments(string[] args) {
|
---|
| 124 | var baseTerminalProbabilityRegex = new Regex(@""--terminalProbBase=(?<prob>.+)"");
|
---|
| 125 | var terminalProbabilityIncRegex = new Regex(@""--terminalProbInc=(?<prob>.+)"");
|
---|
| 126 | var helpRegex = new Regex(@""--help|/\?"");
|
---|
| 127 |
|
---|
| 128 | foreach(var arg in args) {
|
---|
| 129 | var baseTerminalProbabilityMatch = baseTerminalProbabilityRegex.Match(arg);
|
---|
| 130 | var terminalProbabilityIncMatch = terminalProbabilityIncRegex.Match(arg);
|
---|
| 131 | var helpMatch = helpRegex.Match(arg);
|
---|
| 132 | if(helpMatch.Success) { PrintUsage(); Environment.Exit(0); }
|
---|
| 133 | else if(baseTerminalProbabilityMatch.Success) {
|
---|
| 134 | baseTerminalProbability = double.Parse(baseTerminalProbabilityMatch.Groups[""prob""].Captures[0].Value, System.Globalization.CultureInfo.InvariantCulture);
|
---|
| 135 | if(baseTerminalProbability < 0.0 || baseTerminalProbability > 1.0) throw new ArgumentException(""base terminal probability must lie in range [0.0 ... 1.0]"");
|
---|
| 136 | } else if(terminalProbabilityIncMatch.Success) {
|
---|
| 137 | terminalProbabilityInc = double.Parse(terminalProbabilityIncMatch.Groups[""prob""].Captures[0].Value, System.Globalization.CultureInfo.InvariantCulture);
|
---|
| 138 | if(terminalProbabilityInc < 0.0 || terminalProbabilityInc > 1.0) throw new ArgumentException(""terminal probability increment must lie in range [0.0 ... 1.0]"");
|
---|
| 139 | } else {
|
---|
| 140 | Console.WriteLine(""Unknown switch {0}"", arg); PrintUsage(); Environment.Exit(0);
|
---|
| 141 | }
|
---|
| 142 | }
|
---|
[10062] | 143 | }
|
---|
[10100] | 144 | private static void PrintUsage() {
|
---|
| 145 | Console.WriteLine(""Find a solution using random tree search."");
|
---|
| 146 | Console.WriteLine();
|
---|
| 147 | Console.WriteLine(""Parameters:"");
|
---|
| 148 | Console.WriteLine(""\t--terminalProbBase=<prob>\tSets the probability of sampling a terminal alternative in a rule [Default: 0.05]"");
|
---|
| 149 | Console.WriteLine(""\t--terminalProbInc=<prob>\tSets the increment for the probability of sampling a terminal alternative for each level in the syntax tree [Default: 0.05]"");
|
---|
[10062] | 150 | }
|
---|
| 151 |
|
---|
[10100] | 152 |
|
---|
| 153 | private readonly ?IDENT?Problem problem;
|
---|
| 154 | public ?IDENT?Solver(?IDENT?Problem problem) {
|
---|
| 155 | this.problem = problem;
|
---|
[10086] | 156 | }
|
---|
[10067] | 157 |
|
---|
[10062] | 158 | private void Start() {
|
---|
[10086] | 159 | var seedRandom = new Random();
|
---|
[10062] | 160 | var bestF = ?MAXIMIZATION? ? double.NegativeInfinity : double.PositiveInfinity;
|
---|
[10067] | 161 | int n = 0;
|
---|
[10100] | 162 | long sumDepth = 0;
|
---|
| 163 | long sumSize = 0;
|
---|
| 164 | var sumF = 0.0;
|
---|
[10074] | 165 | var sw = new System.Diagnostics.Stopwatch();
|
---|
| 166 | sw.Start();
|
---|
[10080] | 167 | while (true) {
|
---|
[10074] | 168 |
|
---|
[10080] | 169 | // must make sure that calling the start-symbol multiple times in the fitness function always leads to the same path through the grammar
|
---|
| 170 | // so we use a PRNG for generating seeds for a separate PRNG that is reset each time the start symbol is called
|
---|
[10086] | 171 |
|
---|
[10100] | 172 | var _state = new SolverState(problem, seedRandom.Next());
|
---|
[10086] | 173 |
|
---|
[10100] | 174 | var f = problem.Evaluate(_state);
|
---|
| 175 |
|
---|
[10067] | 176 | n++;
|
---|
[10100] | 177 | sumSize += _state.steps;
|
---|
| 178 | sumDepth += _state.depth;
|
---|
| 179 | sumF += f;
|
---|
[10086] | 180 | if (IsBetter(f, bestF)) {
|
---|
| 181 | bestF = f;
|
---|
[10100] | 182 | Console.WriteLine(""{0}\t{1}\t(size={2}, depth={3})"", n, bestF, _state.steps, _state.depth);
|
---|
[10086] | 183 | }
|
---|
| 184 | if (n % 1000 == 0) {
|
---|
[10074] | 185 | sw.Stop();
|
---|
[10100] | 186 | Console.WriteLine(""{0}\tbest: {1:0.000}\t(avg: {2:0.000})\t(avg size: {3:0.0})\t(avg. depth: {4:0.0})\t({5:0.00} sols/ms)"", n, bestF, sumF/1000.0, sumSize/1000.0, sumDepth/1000.0, 1000.0 / sw.ElapsedMilliseconds);
|
---|
[10074] | 187 | sw.Reset();
|
---|
[10100] | 188 | sumSize = 0;
|
---|
| 189 | sumDepth = 0;
|
---|
| 190 | sumF = 0.0;
|
---|
[10074] | 191 | sw.Start();
|
---|
| 192 | }
|
---|
[10062] | 193 | }
|
---|
| 194 | }
|
---|
| 195 |
|
---|
[10100] | 196 | private bool IsBetter(double a, double b) {
|
---|
| 197 | return ?MAXIMIZATION? ? a > b : a < b;
|
---|
[10062] | 198 | }
|
---|
| 199 | }
|
---|
| 200 | }";
|
---|
| 201 |
|
---|
[10335] | 202 | public void Generate(IGrammar grammar, IEnumerable<TerminalNode> terminals, bool maximization, SourceBuilder problemSourceCode) {
|
---|
[10100] | 203 | var solverSourceCode = new SourceBuilder();
|
---|
| 204 | solverSourceCode.Append(solverTemplate)
|
---|
[10335] | 205 | // .Replace("?TERMINALFIELDS?", GenerateTerminalFields(grammar))
|
---|
| 206 | .Replace("?TERMINALNODEDEFINITIONS?", GenerateTerminalNodeDefinitions(terminals))
|
---|
| 207 | // .Replace("?CONSTRUCTORCODE?", GenerateConstructorCode(grammar))
|
---|
[10100] | 208 | .Replace("?MAXIMIZATION?", maximization.ToString().ToLowerInvariant())
|
---|
| 209 | .Replace("?SYMBOLNAMES?", grammar.Symbols.Select(s => s.Name).Aggregate(string.Empty, (str, symb) => str + "\"" + symb + "\", "))
|
---|
| 210 | .Replace("?TRANSITIONTABLE?", GenerateTransitionTable(grammar))
|
---|
| 211 | .Replace("?SUBTREECOUNTTABLE?", GenerateSubtreeCountTable(grammar))
|
---|
| 212 | .Replace("?SAMPLEALTERNATIVECODE?", GenerateSampleAlternativeSource(grammar))
|
---|
[10335] | 213 | // .Replace("?SAMPLETERMINALCODE?", GenerateSampleTerminalSource(grammar))
|
---|
[10100] | 214 | ;
|
---|
[10062] | 215 |
|
---|
[10100] | 216 | problemSourceCode.Append(solverSourceCode.ToString());
|
---|
[10062] | 217 | }
|
---|
| 218 |
|
---|
[10335] | 219 | private string GenerateTerminalNodeDefinitions(IEnumerable<TerminalNode> terminals) {
|
---|
| 220 | var sb = new SourceBuilder();
|
---|
[10062] | 221 |
|
---|
[10335] | 222 | foreach (var terminal in terminals) {
|
---|
| 223 | GenerateTerminalNodeDefinitions(terminal, sb);
|
---|
| 224 | }
|
---|
| 225 | return sb.ToString();
|
---|
| 226 | }
|
---|
[10062] | 227 |
|
---|
[10335] | 228 | private void GenerateTerminalNodeDefinitions(TerminalNode terminal, SourceBuilder sb) {
|
---|
| 229 | sb.AppendFormat("private class {0}Tree {{", terminal.Ident).BeginBlock();
|
---|
| 230 | foreach (var att in terminal.FieldDefinitions) {
|
---|
| 231 | sb.AppendFormat("{0} {1};", att.Type, att.Identifier).AppendLine();
|
---|
| 232 | }
|
---|
| 233 | sb.AppendFormat(" static {0}Tree Create(Random random, ?IDENT?Problem problem) {{", terminal.Ident).BeginBlock();
|
---|
| 234 | sb.AppendFormat("var t = new {0}Tree();", terminal.Ident);
|
---|
| 235 | foreach (var constr in terminal.Constraints) {
|
---|
| 236 | if (constr.Type == ConstraintNodeType.Set) {
|
---|
| 237 | sb.AppendLine("{").BeginBlock();
|
---|
| 238 | sb.AppendFormat(" var elements = problem.GetAllowed{0}_{1}().ToArray();", terminal.Ident, constr.Ident);
|
---|
| 239 | sb.AppendFormat("t.{0} = elements[random.Next(elements.Length)]; ", constr.Ident).AppendLine();
|
---|
| 240 | sb.AppendLine("}").EndBlock();
|
---|
| 241 | } else {
|
---|
| 242 | sb.AppendLine("{").BeginBlock();
|
---|
| 243 | sb.AppendFormat(" var max = problem.GetMax{0}_{1}();", terminal.Ident, constr.Ident);
|
---|
| 244 | sb.AppendFormat(" var min = problem.GetMin{0}_{1}();", terminal.Ident, constr.Ident);
|
---|
| 245 | sb.AppendFormat("t.{0} = random.NextDouble() * (max - min) + min ", constr.Ident).AppendLine();
|
---|
| 246 | sb.AppendLine("}").EndBlock();
|
---|
| 247 | }
|
---|
| 248 | }
|
---|
| 249 | sb.AppendLine("return t;");
|
---|
| 250 | sb.AppendLine("}").EndBlock();
|
---|
| 251 | sb.AppendLine("}").EndBlock();
|
---|
| 252 | }
|
---|
| 253 |
|
---|
| 254 | //private string GenerateSampleTerminalSource(IGrammar grammar) {
|
---|
| 255 | // StringBuilder sb = new StringBuilder();
|
---|
| 256 | // foreach (var t in grammar.TerminalSymbols) {
|
---|
| 257 | // sb.AppendFormat("public void {0}(ISolverState _state, {1}) {{", t.Name, t.GetAttributeString()).AppendLine();
|
---|
| 258 | // foreach (var att in t.Attributes) {
|
---|
| 259 | // // need constraints
|
---|
| 260 | // sb.AppendFormat("{0}", att.Name);
|
---|
| 261 | // }
|
---|
| 262 | // sb.AppendLine("}");
|
---|
| 263 | // }
|
---|
| 264 | // return sb.ToString();
|
---|
| 265 | //}
|
---|
| 266 |
|
---|
| 267 |
|
---|
[10100] | 268 | private string GenerateTransitionTable(IGrammar grammar) {
|
---|
| 269 | Debug.Assert(grammar.Symbols.First().Equals(grammar.StartSymbol));
|
---|
| 270 | var sb = new SourceBuilder();
|
---|
[10086] | 271 |
|
---|
[10100] | 272 | // state idx = idx of the corresponding symbol in the grammar
|
---|
| 273 | var allSymbols = grammar.Symbols.ToList();
|
---|
| 274 | var attributes = new List<string>();
|
---|
| 275 | foreach (var s in grammar.Symbols) {
|
---|
| 276 | var targetStates = new List<int>();
|
---|
| 277 | if (grammar.IsTerminal(s)) {
|
---|
| 278 | foreach (var att in s.Attributes) {
|
---|
| 279 | targetStates.Add(allSymbols.Count + attributes.Count);
|
---|
| 280 | attributes.Add(s.Name + "_" + att);
|
---|
| 281 | }
|
---|
| 282 | } else {
|
---|
| 283 | if (grammar.NumberOfAlternatives(s) > 1) {
|
---|
| 284 | foreach (var alt in grammar.GetAlternatives(s)) {
|
---|
| 285 | // only single-symbol alternatives are supported
|
---|
| 286 | Debug.Assert(alt.Count() == 1);
|
---|
| 287 | targetStates.Add(allSymbols.IndexOf(alt.Single()));
|
---|
| 288 | }
|
---|
| 289 | } else {
|
---|
| 290 | // rule is a sequence of symbols
|
---|
| 291 | var seq = grammar.GetAlternatives(s).Single();
|
---|
| 292 | targetStates.AddRange(seq.Select(symb => allSymbols.IndexOf(symb)));
|
---|
| 293 | }
|
---|
[10067] | 294 | }
|
---|
| 295 |
|
---|
[10100] | 296 | var targetStateString = targetStates.Aggregate(string.Empty, (str, state) => str + state + ", ");
|
---|
[10067] | 297 |
|
---|
[10100] | 298 | var idxOfSourceState = allSymbols.IndexOf(s);
|
---|
| 299 | sb.AppendFormat("// {0}", s).AppendLine();
|
---|
| 300 | sb.AppendFormat("{{ {0} , new int[] {{ {1} }} }},", idxOfSourceState, targetStateString).AppendLine();
|
---|
[10067] | 301 | }
|
---|
[10100] | 302 | for (int attIdx = 0; attIdx < attributes.Count; attIdx++) {
|
---|
| 303 | sb.AppendFormat("// {0}", attributes[attIdx]).AppendLine();
|
---|
| 304 | sb.AppendFormat("{{ {0} , new int[] {{ }} }},", attIdx + allSymbols.Count).AppendLine();
|
---|
| 305 | }
|
---|
| 306 | return sb.ToString();
|
---|
[10067] | 307 | }
|
---|
[10100] | 308 | private string GenerateSubtreeCountTable(IGrammar grammar) {
|
---|
| 309 | Debug.Assert(grammar.Symbols.First().Equals(grammar.StartSymbol));
|
---|
| 310 | var sb = new SourceBuilder();
|
---|
[10067] | 311 |
|
---|
[10100] | 312 | // state idx = idx of the corresponding symbol in the grammar
|
---|
| 313 | var allSymbols = grammar.Symbols.ToList();
|
---|
| 314 | var attributes = new List<string>();
|
---|
| 315 | foreach (var s in grammar.Symbols) {
|
---|
| 316 | int subtreeCount;
|
---|
| 317 | if (grammar.IsTerminal(s)) {
|
---|
| 318 | subtreeCount = s.Attributes.Count();
|
---|
| 319 | attributes.AddRange(s.Attributes.Select(att => s.Name + "_" + att.Name));
|
---|
| 320 | } else {
|
---|
| 321 | if (grammar.NumberOfAlternatives(s) > 1) {
|
---|
| 322 | Debug.Assert(grammar.GetAlternatives(s).All(alt => alt.Count() == 1));
|
---|
| 323 | subtreeCount = 1;
|
---|
| 324 | } else {
|
---|
| 325 | subtreeCount = grammar.GetAlternative(s, 0).Count();
|
---|
| 326 | }
|
---|
[10067] | 327 | }
|
---|
[10100] | 328 |
|
---|
| 329 | sb.AppendFormat("// {0}", s).AppendLine();
|
---|
| 330 | sb.AppendFormat("{{ {0} , {1} }},", allSymbols.IndexOf(s), subtreeCount).AppendLine();
|
---|
[10067] | 331 | }
|
---|
| 332 |
|
---|
[10100] | 333 | for (int attIdx = 0; attIdx < attributes.Count; attIdx++) {
|
---|
| 334 | sb.AppendFormat("// {0}", attributes[attIdx]).AppendLine();
|
---|
| 335 | sb.AppendFormat("{{ {0} , 1 }},", attIdx + allSymbols.Count).AppendLine();
|
---|
[10062] | 336 | }
|
---|
| 337 | return sb.ToString();
|
---|
| 338 | }
|
---|
| 339 |
|
---|
[10100] | 340 | private string GenerateSampleAlternativeSource(IGrammar grammar) {
|
---|
| 341 | Debug.Assert(grammar.Symbols.First().Equals(grammar.StartSymbol));
|
---|
| 342 | var sb = new SourceBuilder();
|
---|
| 343 | int stateCount = 0;
|
---|
| 344 | foreach (var s in grammar.Symbols) {
|
---|
| 345 | sb.AppendFormat("case {0}: ", stateCount++);
|
---|
| 346 | if (grammar.IsTerminal(s)) {
|
---|
[10335] | 347 | // ignore
|
---|
[10100] | 348 | } else {
|
---|
| 349 | var terminalAltIndexes = grammar.GetAlternatives(s)
|
---|
| 350 | .Select((alt, idx) => new { alt, idx })
|
---|
| 351 | .Where((p) => p.alt.All(symb => grammar.IsTerminal(symb)))
|
---|
| 352 | .Select(p => p.idx);
|
---|
| 353 | var nonTerminalAltIndexes = grammar.GetAlternatives(s)
|
---|
| 354 | .Select((alt, idx) => new { alt, idx })
|
---|
| 355 | .Where((p) => p.alt.Any(symb => grammar.IsNonTerminal(symb)))
|
---|
| 356 | .Select(p => p.idx);
|
---|
| 357 | var hasTerminalAlts = terminalAltIndexes.Any();
|
---|
| 358 | var hasNonTerminalAlts = nonTerminalAltIndexes.Any();
|
---|
| 359 | if (hasTerminalAlts && hasNonTerminalAlts) {
|
---|
| 360 | sb.Append("if(random.NextDouble() < TerminalProbForDepth(depth)) {").BeginBlock();
|
---|
| 361 | GenerateReturnStatement(terminalAltIndexes, sb);
|
---|
| 362 | sb.Append("} else {");
|
---|
| 363 | GenerateReturnStatement(nonTerminalAltIndexes, sb);
|
---|
| 364 | sb.Append("}").EndBlock();
|
---|
| 365 | } else {
|
---|
| 366 | GenerateReturnStatement(grammar.NumberOfAlternatives(s), sb);
|
---|
| 367 | }
|
---|
[10062] | 368 | }
|
---|
| 369 | }
|
---|
| 370 | return sb.ToString();
|
---|
| 371 | }
|
---|
[10100] | 372 | private void GenerateReturnStatement(IEnumerable<int> idxs, SourceBuilder sb) {
|
---|
| 373 | if (idxs.Count() == 1) {
|
---|
| 374 | sb.AppendFormat("return {0};", idxs.Single()).AppendLine();
|
---|
[10062] | 375 | } else {
|
---|
[10100] | 376 | var idxStr = idxs.Aggregate(string.Empty, (str, idx) => str + idx + ", ");
|
---|
| 377 | sb.AppendFormat("return new int[] {{ {0} }}[random.Next({1})]; ", idxStr, idxs.Count()).AppendLine();
|
---|
[10062] | 378 | }
|
---|
| 379 | }
|
---|
| 380 |
|
---|
[10100] | 381 | private void GenerateReturnStatement(int nAlts, SourceBuilder sb) {
|
---|
| 382 | if (nAlts > 1) {
|
---|
| 383 | sb.AppendFormat("return random.Next({0});", nAlts).AppendLine();
|
---|
| 384 | } else if (nAlts == 1) {
|
---|
| 385 | sb.AppendLine("return 0; ");
|
---|
[10067] | 386 | } else {
|
---|
[10100] | 387 | sb.AppendLine("throw new InvalidProgramException();");
|
---|
[10062] | 388 | }
|
---|
| 389 | }
|
---|
| 390 | }
|
---|
| 391 | }
|
---|