SIMPLE CODE PARSER
namespace SimpleCOdeParser
{
class Program
{
public static int SearchSymbol(List<Dictionary<String, String>> SymbolTables, String Symbol, out String DataType)
{
for (int i = SymbolTables.Count-1; i >= 0; i--)
{
if (SymbolTables[i].ContainsKey(Symbol))
{
DataType = SymbolTables[i][Symbol];
return i;
}
}
DataType = null;
return -1;
}
public static void Parse(String[] Code)
{
List<Dictionary<String, String>> SymbolTables = new List<Dictionary<string, string>>();
List<String> Output = new List<string>();
int TopOfStack = -1;
for (int i = 0; i < Code.Length; i++)
{
if (Code[i] == "}")
{
SymbolTables.RemoveAt(TopOfStack);
Output.Add("END SCOPE " + TopOfStack + ": " + Code[i]);
TopOfStack--;
}
else if(Code[i] == "{")
{
TopOfStack++;
SymbolTables.Add(new Dictionary<string, string>());
Output.Add("BEG SCOPE " + TopOfStack + ": " + Code[i]);
}
else if(Code[i].StartsWith("int"))
{
String Variable = Code[i].Substring(Code[i].IndexOf(' ')+1,Code[i].Length - Code[i].IndexOf(' ')-1);
SymbolTables[TopOfStack].Add(Variable,Code[i].Substring(0,Code[i].IndexOf(' ')));
Output.Add("DEF SCOPE " + TopOfStack + ": " + Code[i]);
}
else if (Code[i].StartsWith("double"))
{
String Variable = Code[i].Substring(Code[i].IndexOf(' ')+1, Code[i].Length - Code[i].IndexOf(' ')-1);
SymbolTables[TopOfStack].Add(Variable, Code[i].Substring(0, Code[i].IndexOf(' ')));
Output.Add("DEF SCOPE " + TopOfStack + ": " + Code[i]);
}
else if (Code[i].StartsWith("long"))
{
String Variable = Code[i].Substring(Code[i].IndexOf(' ')+1, Code[i].Length - Code[i].IndexOf(' ')-1);
SymbolTables[TopOfStack].Add(Variable, Code[i].Substring(0, Code[i].IndexOf(' ')));
Output.Add("DEF SCOPE " + TopOfStack + ": " + Code[i]);
}
else
{
String DataType = null;
int Scope = SearchSymbol(SymbolTables, Code[i], out DataType);
if(Scope>=0)
Output.Add("USE SCOPE " + Scope + ": " + Code[i] + "("+DataType+")");
}
}
foreach (String x in Output)
{
Console.WriteLine(x);
}
}
static void Main(string[] args)
{
String Code = "{\n"+
"int x\n"+
"{\n"+
"int y\n"+
"int i\n"+
"double s\n"+
"x\n"+
"y\n"+
"i\n"+
"{\n"+
"double x\n"+
"i\n"+
"x\n"+
"x\n"+
"s\n"+
"}\n"+
"{\n"+
"long x\n"+
"s\n"+
"{\n"+
"y\n"+
"x\n"+
"}\n"+
"{\n"+
"y\n"+
"x\n"+
"}\n"+
"x\n"+
"s\n"+
"}\n"+
"x\n"+
"s\n"+
"}\n"+
"}";
string[] CodeFormatted = Code.Split(new char[] {'\n' });
Parse(CodeFormatted);
}
}
}
No comments:
Post a Comment