Files
TextParser/TextParser/Schema/InputSchemaBuilder.cs

106 lines
3.2 KiB
C#

namespace Parsing.Schema;
using Parsing.Schema.BuildingBlocks;
public class InputSchemaBuilder : RepetitionSchemaBuilder<InputSchemaBuilder, InputSchema, InputSchemaContext>, ISchemaBuilder<InputSchema, InputSchemaContext>
{
private InputSchema schema = new InputSchema();
public InputSchemaBuilder()
{
}
public InputSchemaBuilder Expect(InputType type)
{
IBuildingBlock block;
switch (type)
{
case InputType.String:
block = new StringBlock();
break;
case InputType.Integer:
block = new IntegerBlock();
break;
case InputType.Long:
block = new LongBlock();
break;
case InputType.Char:
block = new CharBlock();
break;
default:
throw new Exception("Unrecognized InputType");
}
schema.AddBuildingBlock(block);
return this;
}
public InputSchemaBuilder Expect<T>(InputType type, InputType definedInputType, Func<string, T> wordConverter)
{
IBuildingBlock block;
switch (type)
{
case InputType.Custom:
block = new CustomInputBlock<T>(definedInputType, wordConverter);
break;
default:
throw new Exception("Unrecognized InputType");
}
schema.AddBuildingBlock(block);
return this;
}
public InputSchemaBuilder Repeat(int repetitionCount)
{
// add another layer of parsing
var newInputSchemaBuilder = this.GetNewRepetitionSchemaBuilder(this);
newInputSchemaBuilder.NumRepetition = repetitionCount;
newInputSchemaBuilder.RepetitionType = RepetitionType.FixedRepetition;
return newInputSchemaBuilder;
}
public InputSchemaBuilder Repeat()
{
// add another layer of parsing
var newInputSchemaBuilder = this.GetNewRepetitionSchemaBuilder(this);
newInputSchemaBuilder.RepetitionType = RepetitionType.GreedyRepetition;
return newInputSchemaBuilder;
}
public InputSchemaBuilder EndRepetition()
{
// return back to upper layer of parsing
var currentBuilder = this as InputSchemaBuilder;
if (currentBuilder == null)
{
throw new Exception("Invalid repetition definitions!");
}
var oldSchemaBuilder = currentBuilder.UpperLayerBuilder;
if (oldSchemaBuilder == null)
{
throw new Exception("Something went terribly wrong!");
}
var currentSchema = currentBuilder.Build();
switch (currentBuilder.RepetitionType)
{
case RepetitionType.FixedRepetition:
oldSchemaBuilder.schema.AddBuildingBlock(new FixedRepetitionBlock(currentSchema, currentBuilder.NumRepetition));
break;
case RepetitionType.GreedyRepetition:
oldSchemaBuilder.schema.AddBuildingBlock(new GreedyRepetitionBlock(currentSchema));
break;
default:
throw new Exception("Unrecognized RepetitionType");
}
return oldSchemaBuilder;
}
public InputSchema Build()
{
return schema;
}
}