Hi,
Basically im looking to create a basic C# compiler or parser if you like that will allow users to create simple programs that can declare variables, assign variable values etc.
Ive began with the main functionality within the application, this being the parser which shall pass in user code as a string and delimit this into a series of tokens to determine the command the user wishes to execute. I am trying to use substring to add these string tokens to a String array list but keep getting an out of bounds exception when running this. It appears to work fine for lines of code such as 'int x' but becomes problematic on statements such as 'int x;'. Here is the code for the parser:
using System;
using System.IO;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace Compiler
{
class Parser
{
public String inputCode;
public Interface itf;
//read in lines of code
public StringReader sr;
//array lists to store each line/delimited string tokens of each line
ArrayList pLines;
ArrayList tkns;
int c = 0;
public Parser(Interface inf)
{
itf = inf;
pLines = new ArrayList();
//tkns = new ArrayList();
}
public void parseCode(String parseType)
{
if (parseType.Equals("Run"))
{
//start point to read parsed string
int start = 0;
tkns = new ArrayList();
//get user code
inputCode = itf.UserCode.Text;
//create new string reader - read in lines of code
sr = new StringReader(inputCode);
inputCode = itf.UserCode.Text;
//loop while there is a line to read
while ((inputCode = sr.ReadLine()) != null)
{
for (int i = 0; i < inputCode.Length; i++)
{
if (inputCode[i] == ' ' || inputCode[i] == ';')
{
tkns.Add(inputCode.Substring(start,i));
start = i + 1;
}
}
pLines.Add(tkns);
}
}
}
}
}
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace Compiler
{
public partial class Interface : Form
{
public String pType;
public Interface()
{
InitializeComponent();
}
private void ShowMem_Click(object sender, EventArgs e)
{
Memory mem = new Memory();
mem.Show();
}
private void RunProg_Click(object sender, EventArgs e)
{
pType = "Run";
Parser p = new Parser(this);
p.parseCode(pType);
}
}
}
Just wondering if you could identify why I am getting this exception and a possible solution to this? If this cannot be done using this method, is there a possible alternative that could be implemented to emulate the parser I wish to create?
Thanks for all your help, much appreciated.
Dan