/// <summary> /// 开始调试 /// </summary> public void Run() { // 获取源代码-中间代码信息 intermediateCodeInformations = GetIntermediateCodeInformation(); nextLines = new Dictionary <int, List <int> >(); savedInstructions = new Dictionary <int, IntermediateCode>(); // 获取最大行信息 maxLine = int.MinValue; foreach (int key in intermediateCodeInformations.Keys) { if (key > maxLine) { maxLine = key; } } // 遍历断点信息 foreach (int breakpoint in breakpoints) { // 保存断点处指令并替换为int指令 if (intermediateCodeInformations.ContainsKey(breakpoint)) { IntermediateCodeInformation information = intermediateCodeInformations[breakpoint]; int address = information.Address; IntermediateCode saved = vm.ReplaceWithInt(address); savedInstructions.Add(address, saved); } } vm.Run(); }
protected void Evaluate(IntermediateCode code) { //System.Diagnostics.Debug.WriteLine("KH: " + code); if (code is ICAssignment) { ICAssignment ica = (ICAssignment)code; // create Operation instance ObjectHandle handle = Activator.CreateInstance("JOSPrototype", "JOSPrototype.Runtime.Operation." + ica.op + "OnKH", false, 0, null, new object[] { party, code, program, this }, null, null); Operation op = (Operation)handle.Unwrap(); // execute the operation on EVH op.Run(); } else if (code is ICWhile) { ICWhile icw = (ICWhile)code; WhileOnKH op = new WhileOnKH(party, icw, program, this); op.Run(); } else { ICIfElse icie = (ICIfElse)code; IfElseOnKH op = new IfElseOnKH(party, icie, program, this); op.Run(); } }
public Pascal(String operation, String filePath, String flags) { try{ bool intermediate = flags.IndexOf('i') > 1; bool xref = flags.IndexOf('x') > 1; source = new Source(new StreamReader(filePath)); source.AddMessageListener(new SourceMessageListener()); parser = FrontEndFactory.CreateParser("pascal","top-down",source); parser.AddMessageListener(new ParserMessageListener()); backend = BackendFactory.CreateBackend("compile"); backend.AddMessageListener(new BackendMessageListener()); parser.Parse(); source.close(); intermediateCode = parser.IntermediateCode; symbolTable = Parser.SymbolTable; backend.Process(intermediateCode,symbolTable); } catch(Exception ex){ Console.WriteLine ("Internal translation error"); Console.WriteLine (ex.StackTrace); } }
public override IntermediateCode GenerateIntermediateCode(SyntaxTree tree) { _syntaxTree = tree; _code = new IntermediateCode(); ProcessTree(_syntaxTree); return(_code); }
private void Update() { try { string text = ""; Invoke(() => { text = SourceTextBox.Text; }); List <Error> errors = new List <Error>(); #region Lexical analysis IEnumerable <Error> lexicalErrors = null; IEnumerable <Token> tokens = _translator.Scaner.GetTokens(text, out lexicalErrors); errors.AddRange(lexicalErrors); #endregion #region Syntax analysis if (_translator.Parser != null && errors.Count == 0) { IEnumerable <Error> syntaxErrors = null; _syntaxTree = _translator.Parser.Parse(tokens, out syntaxErrors); errors.AddRange(syntaxErrors); } #endregion #region Semantic analysis if (_translator.SemanticChecker != null && errors.Count == 0) { IEnumerable <Error> semanticErrors = _translator.SemanticChecker.GetSemanticErrors(_syntaxTree); errors.AddRange(semanticErrors); } #endregion #region Codegeneration if (_translator.Generator != null && errors.Count == 0) { _code = _translator.Generator.GenerateIntermediateCode(_syntaxTree); } #endregion var descriptorsPresentation = new DescriptorsPresentation(tokens); Invoke(() => { Errors.Clear(); errors.ForEach((e) => Errors.Add(e)); PresentColoredTokens(tokens, Errors); PresentDescriptorsPresentation(descriptorsPresentation); }); } catch (Exception ex) { MessageBox.Show(ex.Message + "\r\n" + ex.StackTrace); } }
public override void Process(IntermediateCode iCode, SymbolTable symTab) { var startTime = _timeProvider.NowAsUnixTimeMilliseconds(); var executionCount = 0; var runtimeErrors = 0; SendMessage(new Message.Message(MessageType.INTERPRETER_SUMMARY, new object[] { executionCount, runtimeErrors, _timeProvider.ElapsedTimeSinceInSeconds(startTime) })); }
public override void Process(IntermediateCode iCode, SymbolTable symTab) { var startTime = _timeProvider.NowAsUnixTimeMilliseconds(); int instructionCount = 0; // Send the parser summary message. SendMessage(new Message.Message(MessageType.COMPILER_SUMMARY, new object[] { instructionCount, _timeProvider.ElapsedTimeSinceInSeconds(startTime) })); }
private void AddDependency(IntermediateCode from, IntermediateCode to, DependencyType dt) { if (!from.outEdge.ContainsKey(to)) { from.outEdge.Add(to, new HashSet <DependencyType>()); } from.outEdge[to].Add(dt); if (!to.inEdge.ContainsKey(from)) { to.inEdge.Add(from, new HashSet <DependencyType>()); } to.inEdge[from].Add(dt); }
protected void onEjecutarCodigoIntermedio(object sender, EventArgs e) { if (arbolCompilador == null) { return; } IntermediateCode intermediateCode = new IntermediateCode(arbolCompilador); intermediateCode.ejectIntermediateCode(); textview12.Buffer.Text = IntermediateCode.codigoIntermedio; }
/// <summary> /// 移除断点 /// </summary> /// <param name="breakpoint">断点行号</param> public void RemoveBreakpoint(int breakpoint) { // 移除断点 breakpoints.Remove(breakpoint); // 恢复原始中间指令 IntermediateCodeInformation information = intermediateCodeInformations[breakpoint]; int address = information.Address; IntermediateCode saved = savedInstructions[address]; savedInstructions.Remove(address); vm.Resume(address, saved); }
/// <summary> /// 增加断点 /// </summary> /// <param name="breakpoint">断点行号</param> public void AddBreakpoint(int breakpoint) { // 寻找插入位置 int index = 0, length = breakpoints.Count; while (index < length && breakpoints[index] < breakpoint) { index++; } breakpoints.Insert(index, breakpoint); // 保存并替换中间指令为int IntermediateCodeInformation information = intermediateCodeInformations[breakpoint]; int address = information.Address; IntermediateCode saved = vm.ReplaceWithInt(address); savedInstructions.Add(address, saved); }
/// <summary> /// 获取源代码-中间代码信息 /// </summary> /// <returns>源代码中间代码信息</returns> private Dictionary <int, IntermediateCodeInformation> GetIntermediateCodeInformation() { int length = codesArray.Count; Dictionary <int, IntermediateCodeInformation> informations = new Dictionary <int, IntermediateCodeInformation>(); // 遍历中间代码 for (int i = 0; i < length; i++) { IntermediateCode current = codesArray[i]; int currentLine = current.lineNum; IntermediateCodeInformation currentInformation; // 判断该中间指令对应源代码的行是否已经加入信息表中 if (informations.TryGetValue(currentLine, out currentInformation)) { // 该行含函数调用则更新函数入口地址列表 if (current.type == InstructionType.call) { currentInformation.IsFunctionCall = true; currentInformation.FuncionEntryList.AddLast((int)current.operant); currentInformation.IsFunctionBody = false; informations[currentLine] = currentInformation; } } else { // 该行源代码首条中间指令 currentInformation = new IntermediateCodeInformation(); currentInformation.Address = i; currentInformation.Line = currentLine; currentInformation.IsFunctionCall = false; currentInformation.FuncionEntryList = new LinkedList <int>(); currentInformation.IsFunctionBody = false; informations.Add(currentLine, currentInformation); } } foreach (FunctionInformation information in functionInformationTable.Values) { int line = codesArray[information.enrtyAddress].lineNum; informations[line].IsFunctionBody = true; } return(informations); }
/// <summary> /// 处理中断 /// </summary> private void HandleInterrupt() { NeedDebug?.Invoke(); // 挂起调试器进程等待用户操作 Thread.CurrentThread.Suspend(); // 根据用户输入决定调试模式 switch (mode) { case -1: vm.Stop(); break; case 0: // Step into模式 // 根据当前行号获取保存的中间代码 int line0 = vm.GetLastCodeInformation().Line; IntermediateCodeInformation information0 = intermediateCodeInformations[line0]; int address0 = information0.Address; IntermediateCode saved = savedInstructions[address0]; // 查询当前行是否为函数调用 if (information0.IsFunctionCall) { // 对函数入口表中的每一个函数入口指令进行保存并替换int指令 foreach (int functionEntry in information0.FuncionEntryList) { if (!savedInstructions.ContainsKey(functionEntry)) { IntermediateCode function = vm.ReplaceWithInt(functionEntry); savedInstructions.Add(functionEntry, function); } } } // 单条执行中间代码 vm.InterpretSingleInstruction(saved); // 对下一行源代码对应的中间代码进行保存并替换int ReplaceNextLine(line0); break; case 1: // Step over模式 // 根据当前行号获取保存的中间代码 int line1 = vm.GetLastCodeInformation().Line; IntermediateCodeInformation information1 = intermediateCodeInformations[line1]; int address1 = information1.Address; IntermediateCode saved1 = savedInstructions[address1]; // 单条执行中间代码 vm.InterpretSingleInstruction(saved1); // 对下一行源代码对应的中间代码进行保存并替换int ReplaceNextLine(line1); break; case 2: // Continue模式 // 根据当前行号获取保存的中间代码 int line2 = vm.GetLastCodeInformation().Line; IntermediateCodeInformation information2 = intermediateCodeInformations[line2]; int address2 = information2.Address; IntermediateCode saved2 = savedInstructions[address2]; // 单条执行中间代码 vm.InterpretSingleInstruction(saved2); break; default: // 其他模式 break; } }
protected Parser(Scanner Scanner) { this.Scanner = Scanner; this.IntermediateCode = null; }
public CodeLogItem(IntermediateCode code) { Code = code; }
public ContextualLine(ILine line, IntermediateCode generator, string description) { Line = line; Generator = generator; Description = description; }
public void LogVisitFor(IntermediateCode code) { }
// out most while loop or if-else statement, instantiated by party protected OperationOnEVH(Party party, IntermediateCode code, Program program, OperationType opType) : base(party, code.index, null, null, opType) { this.program = program; }
public void LoadCode(IntermediateCode code) { CodeList.ItemsSource = code.Instructions; }
// nested while loop or if-else, instantiated by another loop or if-else protected OperationOnKH(Party party, IntermediateCode code, Program program, Operation caller, OperationType opType) : base(party, code.index, caller, null, opType) { //isCalledByParty = true; this.program = program; }
private bool IsDependent(IntermediateCode codei, IntermediateCode codej) { if (codei is ICAssignment && codej is ICAssignment) { ICAssignment assignmenti = (ICAssignment)codei, assignmentj = (ICAssignment)codej; if (ETerminal.IsEqual(assignmenti.result, assignmentj.result) || ETerminal.IsEqual(assignmentj.result, assignmenti.operand1) || ETerminal.IsEqual(assignmentj.result, assignmenti.operand2) || ETerminal.IsEqual(assignmenti.result, assignmentj.operand1) || ETerminal.IsEqual(assignmenti.result, assignmentj.operand2)) { return(true); } return(false); } else if (codei is ICAssignment && codej is ICWhile) { ICAssignment assignmenti = (ICAssignment)codei; ICWhile whilej = (ICWhile)codej; if (ETerminal.IsEqual(assignmenti.result, whilej.condition)) { return(true); } foreach (var entry in whilej.conditionCodes.GetCodes()) { if (IsDependent(assignmenti, entry)) { return(true); } } foreach (var entry in whilej.codes.GetCodes()) { if (IsDependent(assignmenti, entry)) { return(true); } } return(false); } else if (codei is ICWhile && codej is ICAssignment) { ICWhile whilei = (ICWhile)codei; ICAssignment assignmentj = (ICAssignment)codej; if (ETerminal.IsEqual(assignmentj.result, whilei.condition)) { return(true); } foreach (var entry in whilei.conditionCodes.GetCodes()) { if (IsDependent(entry, assignmentj)) { return(true); } } foreach (var entry in whilei.codes.GetCodes()) { if (IsDependent(entry, assignmentj)) { return(true); } } return(false); } else if (codei is ICWhile && codej is ICWhile) { ICWhile whilei = (ICWhile)codei, whilej = (ICWhile)codej; List <IntermediateCode> codesi = new List <IntermediateCode>(), codesj = new List <IntermediateCode>(); codesi.AddRange(whilei.conditionCodes.GetCodes()); codesi.AddRange(whilei.codes.GetCodes()); codesj.AddRange(whilej.conditionCodes.GetCodes()); codesj.AddRange(whilej.codes.GetCodes()); foreach (var entryi in codesi) { foreach (var entryj in codesj) { if (IsDependent(entryi, entryj)) { return(true); } } } return(false); } else if (codei is ICAssignment && codej is ICIfElse) { ICAssignment assignmenti = (ICAssignment)codei; ICIfElse ifelsej = (ICIfElse)codej; if (ETerminal.IsEqual(assignmenti.result, ifelsej.condition)) { return(true); } List <IntermediateCode> codesj = new List <IntermediateCode>(); codesj.AddRange(ifelsej.conditionCodes.GetCodes()); codesj.AddRange(ifelsej.codesIf.GetCodes()); codesj.AddRange(ifelsej.codesElse.GetCodes()); foreach (var entry in codesj) { if (IsDependent(assignmenti, entry)) { return(true); } } return(false); } else if (codei is ICIfElse && codej is ICAssignment) { ICIfElse ifelsei = (ICIfElse)codei; ICAssignment assignmentj = (ICAssignment)codej; if (ETerminal.IsEqual(assignmentj.result, ifelsei.condition)) { return(true); } List <IntermediateCode> codesi = new List <IntermediateCode>(); codesi.AddRange(ifelsei.conditionCodes.GetCodes()); codesi.AddRange(ifelsei.codesIf.GetCodes()); codesi.AddRange(ifelsei.codesElse.GetCodes()); foreach (var entry in codesi) { if (IsDependent(entry, assignmentj)) { return(true); } } return(false); } else if (codei is ICWhile && codej is ICIfElse) { ICWhile whilei = (ICWhile)codei; ICIfElse ifelsej = (ICIfElse)codej; List <IntermediateCode> codesi = new List <IntermediateCode>(), codesj = new List <IntermediateCode>(); codesi.AddRange(whilei.conditionCodes.GetCodes()); codesi.AddRange(whilei.codes.GetCodes()); codesj.AddRange(ifelsej.conditionCodes.GetCodes()); codesj.AddRange(ifelsej.codesIf.GetCodes()); codesj.AddRange(ifelsej.codesElse.GetCodes()); foreach (var entryi in codesi) { foreach (var entryj in codesj) { if (IsDependent(entryi, entryj)) { return(true); } } } return(false); } else if (codei is ICIfElse && codej is ICWhile) { ICIfElse ifelsei = (ICIfElse)codei; ICWhile whilej = (ICWhile)codej; List <IntermediateCode> codesi = new List <IntermediateCode>(), codesj = new List <IntermediateCode>(); codesi.AddRange(ifelsei.conditionCodes.GetCodes()); codesi.AddRange(ifelsei.codesIf.GetCodes()); codesi.AddRange(ifelsei.codesElse.GetCodes()); codesj.AddRange(whilej.conditionCodes.GetCodes()); codesj.AddRange(whilej.codes.GetCodes()); foreach (var entryi in codesi) { foreach (var entryj in codesj) { if (IsDependent(entryi, entryj)) { return(true); } } } return(false); } else { ICIfElse ifelsei = (ICIfElse)codei; ICIfElse ifelsej = (ICIfElse)codej; List <IntermediateCode> codesi = new List <IntermediateCode>(), codesj = new List <IntermediateCode>(); codesi.AddRange(ifelsei.conditionCodes.GetCodes()); codesi.AddRange(ifelsei.codesIf.GetCodes()); codesi.AddRange(ifelsei.codesElse.GetCodes()); codesj.AddRange(ifelsej.conditionCodes.GetCodes()); codesj.AddRange(ifelsej.codesIf.GetCodes()); codesj.AddRange(ifelsej.codesElse.GetCodes()); foreach (var entryi in codesi) { foreach (var entryj in codesj) { if (IsDependent(entryi, entryj)) { return(true); } } } return(false); } }
public abstract void Process(IntermediateCode iCode, SymbolTable symTab);
public static void Main(string[] args) { string baseDirectory = string.Empty; #if (NOTCORE) baseDirectory = AppDomain.CurrentDomain.BaseDirectory; #endif #if (NETCORE) baseDirectory = AppContext.BaseDirectory; #endif Console.WriteLine("Super Basic Front-End Executor"); if (args.Length != 3) { Console.WriteLine("\n\nWrong param passed"); Console.WriteLine("Param : SuperBasic [file] [gen] [genopt]"); } else { string filePath = args[0]; string gen = args[1]; string genopt = args[2]; Stopwatch time = new Stopwatch(); LexicalAnalyzer la = new LexicalAnalyzer(baseDirectory); Console.WriteLine("Loading file...."); string codeLoaded = File.ReadAllText(filePath); Console.WriteLine("Readed " + codeLoaded.Length + " words.\n\n"); Console.WriteLine("Lexeical analyzing.."); time.Start(); if (!la.LoadSource(codeLoaded)) { Console.WriteLine("Source code analysis failed"); Console.ReadLine(); return; } time.Stop(); Console.WriteLine("Elapsed : " + time.ElapsedMilliseconds + " ms"); Console.WriteLine("Readed " + la.Tokens.Count() + " Tokens\n\n"); Console.WriteLine("Parser to: " + gen); if (gen == "cpp") { IntermediateCode.SetIO(new CppTextIO()); IntermediateCode.SetGenerator(new CppGenerator(genopt)); } Console.WriteLine("Generator Param: " + genopt); Parser p = new Parser(la); Console.WriteLine("\n\nParsering..."); try { time.Reset(); time.Start(); p.Program(); time.Stop(); Console.WriteLine("Elapsed : " + time.ElapsedMilliseconds + " ms"); Console.WriteLine("Intermedia Code Generated : " + IntermediateCode.CurrentIO.ToString().Length + " Bytes\n\n"); } catch (Exception e) { Console.WriteLine("Exception raised while parsering"); Console.WriteLine(e.Message); return; } string filename = Path.GetFileNameWithoutExtension(filePath); string output = Path.Combine(baseDirectory, filename + "." + IntermediateCode.CurrentIO.FileExt()); Console.WriteLine("Output to :" + output + "\n\n"); File.WriteAllText(output, IntermediateCode.CurrentIO.ToString()); Console.WriteLine("Done."); } }
public override void Process(IntermediateCode iCode, SymbolTable symTab) { }
private void ReplaceNextLine(int line) { // 如果当前行不是最后一行 if (line != maxLine) { // 判断是否已缓存该行的下一行 if (!nextLines.ContainsKey(line)) { // 判断是否为函数体的行 int functionEntry = -1; foreach (FunctionInformation information in functionInformationTable.Values) { if (information.enrtyAddress <= intermediateCodeInformations[line].Address && information.outAddress >= intermediateCodeInformations[line].Address) { functionEntry = information.enrtyAddress; break; } } if (functionEntry != -1) { // 若是函数体中的断点则判断是否被调用 foreach (KeyValuePair <int, IntermediateCodeInformation> information in intermediateCodeInformations) { IntermediateCodeInformation currentInforamtion = information.Value; if (currentInforamtion.IsFunctionCall && currentInforamtion.FuncionEntryList.Contains(functionEntry)) { // 若被调用则获取调用语句的下一行 // 同时保存该行的下一行 if (information.Key != maxLine) { int nextLine = GetNextLine(information.Key); while (intermediateCodeInformations[nextLine].IsFunctionBody && nextLine < maxLine) { nextLine = GetNextLine(nextLine); } nextLines.Add(line, new List <int> { GetNextLine(line), nextLine }); break; } else { return; } } } } else { // 非函数体中的直接获取下一行 int nextLine = GetNextLine(line); while (intermediateCodeInformations[nextLine].IsFunctionBody && nextLine < maxLine) { nextLine = GetNextLine(nextLine); } nextLines.Add(line, new List <int> { nextLine }); } } foreach (int nextLine in nextLines[line]) { // 对下一行源代码对应的中间代码进行保存并替换int IntermediateCodeInformation nextLineInformation = intermediateCodeInformations[nextLine]; int nextLineAddress = nextLineInformation.Address; if (!savedInstructions.ContainsKey(nextLineAddress)) { IntermediateCode nextLineSaved = vm.ReplaceWithInt(nextLineAddress); savedInstructions.Add(nextLineAddress, nextLineSaved); } } } }
protected Parser(IScanner scanner, IMessageHandler messageHandler) { _messageHandler = messageHandler; Scanner = scanner; _intermediateCode = null; }
public override void Process(IntermediateCode interMediateCode, SymbolTable symbolTable) { int instructionCount = 0; SendMessage (new Message(MessageType.COMPILER_SUMMARY,new object[]{instructionCount})); }
public abstract void Process(IntermediateCode interMediateCode, SymbolTable symbolTable);