public static string Reformat(string input, ref int cursorPosition, out int scopeStart, out int scopeLength) { //return null; // uncomment to disable formatting var oldCaret = cursorPosition; scopeStart = 0; scopeLength = 0; try { // Example of reformatting: var sourceCodeReader = new SourceCodeTokeniser(); var program = sourceCodeReader.Read(input, true); var sb = new StringBuilder(); var focus = program.Reformat(0, sb, ref cursorPosition); if (focus != null && focus != program) { scopeStart = focus.FormattedLocation; scopeLength = focus.FormattedLength; } return(sb.ToString()); } catch { cursorPosition = oldCaret; return(null); } }
// ReSharper disable once UnusedMember.Global /// <summary> /// Start with source code, and run program to termination /// </summary> /// <param name="languageInput">Source code</param> /// <param name="input">User typing input (for readline / readkey etc)</param> /// <param name="output">Print output from the program</param> /// <param name="trace">Flag. If true, write the entire interpreter flow to output</param> /// <param name="printIL">Flag. If true, write a view of the bytecode IL to output</param> /// <param name="traceMemory">Flag. If true, write memory and GC state</param> /// <returns>Run time, excluding compile time</returns> public static TimeSpan BuildAndRun(string languageInput, TextReader input, TextWriter output, bool trace, bool printIL, bool traceMemory) { // Compile var sourceCodeReader = new SourceCodeTokeniser(); var program = sourceCodeReader.Read(languageInput, false); if (!program.IsValid) { output.WriteLine("Program is not well formed"); // TODO: be more helpful return(TimeSpan.Zero); } ToNanCodeCompiler.BaseDirectory = baseDirectory; var compiledOutput = ToNanCodeCompiler.CompileRoot(program, debug: false); // Load var stream = new MemoryStream(); compiledOutput.WriteToStream(stream); stream.Seek(0, SeekOrigin.Begin); var memoryModel = new RuntimeMemoryModel(stream); if (printIL) { output.WriteLine("======= BYTE CODE SUMMARY =========="); compiledOutput.AddSymbols(ByteCodeInterpreter.DebugSymbolsForBuiltIns()); output.WriteLine(memoryModel.ToString(compiledOutput.GetSymbols())); output.WriteLine("===================================="); } // Execute var sw = new Stopwatch(); var interpreter = new ByteCodeInterpreter(); try { // Init the interpreter. interpreter.Init(memoryModel, input, output, debugSymbols: compiledOutput.GetSymbols()); sw.Start(); interpreter.Execute(false, trace, false); sw.Stop(); if (traceMemory) { output.WriteLine("======== GARBAGE SUMMARY ==========="); foreach (var token in memoryModel.Variables.PotentialGarbage) { output.WriteLine(NanTags.Describe(token)); } output.WriteLine("===================================="); } return(sw.Elapsed); } catch (Exception e) { output.WriteLine("Interpreter stopped at " + interpreter.LastPosition()); output.WriteLine("Exception : " + e.Message); output.WriteLine("\r\n\r\n" + e.StackTrace); sw.Stop(); return(sw.Elapsed); } }
private double EvaluateBuiltInFunction(ref int position, FuncDef kind, int nbParams, double[] param, Stack <int> returnStack, Stack <double> valueStack) { switch (kind) { // each element equal to the first case FuncDef.Equal: if (nbParams < 2) { throw new Exception("equals ( = ) must have at least two things to compare"); } return(NanTags.EncodeBool(ListEquals(param))); // Each element smaller than the last case FuncDef.GreaterThan: if (nbParams < 2) { throw new Exception("greater than ( > ) must have at least two things to compare"); } return(NanTags.EncodeBool(FoldGreaterThan(param))); // Each element larger than the last case FuncDef.LessThan: if (nbParams < 2) { throw new Exception("less than ( < ) must have at least two things to compare"); } return(NanTags.EncodeBool(FoldLessThan(param))); // Each element DIFFERENT TO THE FIRST (does not check set uniqueness!) case FuncDef.NotEqual: if (nbParams < 2) { throw new Exception("not-equal ( <> ) must have at least two things to compare"); } return(NanTags.EncodeBool(!ListEquals(param))); case FuncDef.Assert: if (nbParams < 1) { return(NanTags.VoidReturn()); // assert nothing passes } var condition = param.ElementAt(0); if (_memory.CastBoolean(condition) == false) { var msg = ConcatList(param, 1); throw new Exception("Assertion failed: " + msg); } return(NanTags.VoidReturn()); case FuncDef.Random: if (nbParams < 1) { return(rnd.NextDouble()); // 0 params - any size } if (nbParams < 2) { return(rnd.Next(_memory.CastInt(param.ElementAt(0)))); // 1 param - max size } return(rnd.Next(_memory.CastInt(param.ElementAt(0)), _memory.CastInt(param.ElementAt(1)))); // 2 params - range case FuncDef.Eval: var reader = new SourceCodeTokeniser(); var statements = _memory.CastString(param.ElementAt(0)); var programTmp = reader.Read(statements, false); var bin = ToNanCodeCompiler.CompileRoot(programTmp, false); var interpreter = new ByteCodeInterpreter(); interpreter.Init(new RuntimeMemoryModel(bin, _memory.Variables), _input, _output, DebugSymbols); return(interpreter.Execute(false, _runningVerbose, false).Result); case FuncDef.Call: NanTags.DecodePointer(param.ElementAt(0), out var target, out var type); if (type != DataType.PtrString && type != DataType.PtrStaticString) { throw new Exception("Tried to call a function by name, but passed a '" + type + "' at " + position); } // this should be a string, but we need a function name hash -- so calculate it: var strName = _memory.DereferenceString(target); var functionNameHash = NanTags.GetCrushedName(strName); nbParams--; var newParam = param.Skip(1).ToArray(); return(EvaluateFunctionCall(ref position, functionNameHash, nbParams, newParam, returnStack, valueStack)); case FuncDef.LogicNot: if (nbParams != 1) { throw new Exception("'not' should be called with one argument"); } var bval = _memory.CastBoolean(param.ElementAt(0)); return(NanTags.EncodeBool(!bval)); case FuncDef.LogicOr: { bool more = nbParams > 0; int i = 0; while (more) { var bresult = _memory.CastBoolean(param.ElementAt(i)); if (bresult) { return(NanTags.EncodeBool(true)); } i++; more = i < nbParams; } return(NanTags.EncodeBool(false)); } case FuncDef.LogicAnd: { bool more = nbParams > 0; int i = 0; while (more) { var bresult = _memory.CastBoolean(param.ElementAt(i)); if (!bresult) { return(NanTags.EncodeBool(false)); } i++; more = i < nbParams; } return(NanTags.EncodeBool(true)); } case FuncDef.ReadKey: return(_memory.StoreStringAndGetReference(((char)_input.Read()).ToString())); case FuncDef.ReadLine: return(_memory.StoreStringAndGetReference(_input.ReadLine())); case FuncDef.Print: { string lastStr = null; foreach (var v in param) { lastStr = _memory.CastString(v); _output.Write(lastStr); } if (lastStr != "") { _output.WriteLine(); } } return(NanTags.VoidReturn()); case FuncDef.Substring: if (nbParams == 2) { var newString = _memory.CastString(param.ElementAt(0)).Substring(_memory.CastInt(param.ElementAt(1))); return(_memory.StoreStringAndGetReference(newString)); } else if (nbParams == 3) { int start = _memory.CastInt(param.ElementAt(1)); int length = _memory.CastInt(param.ElementAt(2)); string s = _memory.CastString(param.ElementAt(0)).Substring(start, length); return(_memory.StoreStringAndGetReference(s)); } else { throw new Exception("'Substring' should be called with 2 or 3 parameters"); } case FuncDef.Length: return(_memory.CastString(param.ElementAt(0)).Length); case FuncDef.Replace: if (nbParams != 3) { throw new Exception("'Replace' should be called with 3 parameters"); } string exp = _memory.CastString(param.ElementAt(0)); string oldValue = _memory.CastString(param.ElementAt(1)); string newValue = _memory.CastString(param.ElementAt(2)); exp = exp.Replace(oldValue, newValue); return(_memory.StoreStringAndGetReference(exp)); case FuncDef.Concat: var builder = new StringBuilder(); foreach (var v in param) { builder.Append(_memory.CastString(v)); } return(_memory.StoreStringAndGetReference(builder.ToString())); case FuncDef.UnitEmpty: { // valueless marker (like an empty object) return(NanTags.EncodeNonValue(NonValueType.Unit)); } case FuncDef.MathAdd: if (nbParams == 1) { return(param[0]); } return(param.ChainSum()); case FuncDef.MathSub: if (nbParams == 1) { return(-param[0]); } return(param.ChainDifference()); case FuncDef.MathProd: if (nbParams == 1) { throw new Exception("Uniary '*' is not supported"); } return(param.ChainProduct()); case FuncDef.MathDiv: if (nbParams == 1) { throw new Exception("Uniary '/' is not supported"); } return(param.ChainDivide()); case FuncDef.MathMod: if (nbParams == 1) { return(param[0] % 2); } return(param.ChainRemainder()); default: throw new Exception("Unrecognised built-in! Type = " + ((int)kind)); } }