-
Notifications
You must be signed in to change notification settings - Fork 0
/
RPElementBuilder.cs
69 lines (52 loc) · 2.53 KB
/
RPElementBuilder.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
namespace RoslynPath
{
internal class RPElementBuilder : IRPElementBuilder
{
protected Dictionary<string, string> Options { get; set; }
public IRPElement Element { get; protected set; }
private static readonly Dictionary<Type, Type> _rpTokenTypeRPElementBuilderPairs;
static RPElementBuilder()
{
_rpTokenTypeRPElementBuilderPairs = new Dictionary<Type, Type>();
IEnumerable<Type> concreteElementBuilders = Assembly.GetExecutingAssembly().GetTypes()
.Where(t => typeof(IRPElementBuilder).IsAssignableFrom(t) && !t.IsAbstract && !t.IsInterface);
foreach (Type concreteElementBuilder in concreteElementBuilders)
{
RPElementBuilderAttribute attribute = concreteElementBuilder.GetCustomAttributes(typeof(RPElementBuilderAttribute), false)
.Cast<RPElementBuilderAttribute>()
// Only one RPElementBuilderAttribute is allowed
.FirstOrDefault();
if (attribute != null)
_rpTokenTypeRPElementBuilderPairs[attribute.TokenType] = concreteElementBuilder;
}
}
public RPElementBuilder() { }
protected RPElementBuilder(Dictionary<string, string> options, IRPElement element)
{
Options = options;
Element = element;
}
public void Clean()
{
Options = new Dictionary<string, string>();
Element = null;
}
public virtual int ConvertTokens(IEnumerable<RPToken> tokens)
{
RPToken token = tokens.First();
if (!_rpTokenTypeRPElementBuilderPairs.ContainsKey(token.TokenType))
throw new Exception($"{token.TokenType} does not have an associated RPElementBuilder");
Type rpElementBuilderType = _rpTokenTypeRPElementBuilderPairs[token.TokenType];
if (rpElementBuilderType.GetMethod("ConvertTokens").DeclaringType == typeof(RPElementBuilder))
throw new Exception($"{rpElementBuilderType} does not implement the ConvertTokens method.");
IRPElementBuilder elementBuilder = (IRPElementBuilder)Activator.CreateInstance(rpElementBuilderType, new object[] { Options, Element });
int tokensConsumed = elementBuilder.ConvertTokens(tokens);
Element = elementBuilder.Element;
return tokensConsumed;
}
}
}