/// <summary> /// Convert Character constant array to symbol array. /// </summary> /// <param name="argument"></param> /// <returns></returns> private AType Compute(AType argument) { //If argument is character constant or character constant vector then we convert it symbol, //and cut blanks from end. if (argument.Rank <= 1) { return(ASymbol.Create(argument.ToString().TrimEnd())); } else { AType result = AArray.Create(ATypes.ASymbol); foreach (AType item in argument) { result.AddWithNoUpdate(Compute(item)); } result.Length = argument.Length; result.Shape = new List <int>(); result.Shape.AddRange(argument.Shape.GetRange(0, argument.Shape.Count - 1)); result.Rank = argument.Rank - 1; return(result); } }
/// <summary> /// Extracts the path from the supplied <see cref="pathArgument"/>. /// </summary> /// <param name="pathArgument">Must be a Char or Symbol type.</param> /// <param name="environment"></param> /// <returns> /// Absolute path if the <see cref="pathArgument"/> is a relative/absoulte path. /// Name of the file extracted from the <see cref="pathArgument"/> if it is not a relative/absolute path. /// Null if the supplied <see cref="AType"/> has an incorrect type. /// </returns> internal static string GetFullPathOrValue(AType pathArgument, Aplus environment) { if (pathArgument.Type != ATypes.AChar && pathArgument.Type != ATypes.ASymbol) { return(null); } AType raveled = pathArgument.Rank > 1 ? MonadicFunctionInstance.Ravel.Execute(pathArgument, environment) : pathArgument; string path; if (raveled.Type == ATypes.AChar) { path = raveled.ToString(); } else if (raveled.Rank > 0) { path = raveled.Length > 0 ? raveled[0].asString : ""; } else { path = raveled.asString; } if (!String.IsNullOrEmpty(path) && !Path.IsPathRooted(path) && !String.IsNullOrEmpty(Path.GetDirectoryName(path))) { path = Path.GetFullPath(path); } return(path); }
protected override int RunFile(ScriptSource source) { if (this.ScriptScope == null) { this.ScriptScope = this.Engine.CreateScope(); this.ScriptScope.SetVariable( "time", AFunc.Create( "time", (Func <Aplus, AType>)Time, 1, "returns the user time of the current process" ) ); } try { AType result = source.Execute <AType>(this.ScriptScope); Console.WriteLine(result.ToString(), Style.Out); } catch (Error error) { Console.ErrorOutput.Write(error); return(1); } catch (Exception) { throw; } return(0); }
/// <summary> /// Convert Character constant array to symbol array. /// </summary> /// <param name="argument"></param> /// <returns></returns> private AType Compute(AType argument) { //If argument is character constant or character constant vector then we convert it symbol, //and cut blanks from end. if (argument.Rank <= 1) { return ASymbol.Create(argument.ToString().TrimEnd()); } else { AType result = AArray.Create(ATypes.ASymbol); foreach (AType item in argument) { result.AddWithNoUpdate(Compute(item)); } result.Length = argument.Length; result.Shape = new List<int>(); result.Shape.AddRange(argument.Shape.GetRange(0, argument.Shape.Count - 1)); result.Rank = argument.Rank - 1; return result; } }
public void SpawnAlly(AType type, int amount) { for (int i = 0; i < amount; i++) { Spawn("Ally", type.ToString()); } main.UpdateScale(AType.Eagle, amount, false); }
// Todo: extend it to correctly return the values like the original a+ interpreter public static string FormatAType(AType value, Aplus runtime) { if (value.IsBox || ((value is AReference) && ((AReference)value).Data is AFunc)) { return(value.ToString()); } return(Function.Monadic.MonadicFunctionInstance.DefaultFormat.Execute( value, runtime ).ToString()); }
private static void ExtractRows(AType argument, Queue <string> rows) { if (argument.Rank > 1) { foreach (AType item in argument) { ExtractRows(item, rows); } } else { rows.Enqueue(argument.ToString()); } }
private static void ExtractRows(AType argument, Queue<string> rows) { if (argument.Rank > 1) { foreach (AType item in argument) { ExtractRows(item, rows); } } else { rows.Enqueue(argument.ToString()); } }
protected override byte[] ConvertToByte(AType message) { if (message.Type != ATypes.AChar) { throw new ADAPException(ADAPExceptionType.Export); } byte[] messageBody = ASCIIEncoder.GetBytes(message.ToString()); byte[] messageHeader = BitConverter.GetBytes(IPAddress.HostToNetworkOrder(messageBody.Length)); List<byte> result = new List<byte>(); result.AddRange(messageHeader); result.AddRange(messageBody); return result.ToArray(); }
internal static AType Loadfile(Aplus environment, AType filename) { string fileName = filename.ToString(); if (filename.Type != ATypes.AChar) { throw new Error.Type("_loadfile"); } if (!File.Exists(fileName)) { throw new Error.Invalid("_loadfile"); } AType result = AArray.Create(ATypes.AChar); using (FileStream fileStream = new FileStream(fileName, FileMode.Open)) { int blockReadSize = 5 * 1024; // 5 KiB long totalSize = fileStream.Length; int readLength = blockReadSize < totalSize ? blockReadSize : (int)totalSize; byte[] filePartialContent = new byte[readLength]; int sum = 0; // total number of bytes read int count; // current number of bytes read // read until Read method returns 0 (end of the stream has been reached) while ((count = fileStream.Read(filePartialContent, 0, readLength)) > 0) { sum += count; // sum is a buffer offset for next reading // build the array from the bytes that was read for (int i = 0; i < count; i++) { result.Add(AChar.Create((char)filePartialContent[i])); } // calculate the next size of the read block long leftover = totalSize - sum; readLength = blockReadSize < leftover ? blockReadSize : (int)leftover; } return(result); } }
internal static AType GetSystemVariable(Aplus environment, AType input) { ATypes type = input.Type; if (type != ATypes.ASymbol && type != ATypes.AChar) { throw new Error.Type("_gsv"); } string name = (type == ATypes.ASymbol) ? input.asString : input.ToString(); if(!environment.SystemVariables.Contains(name)) { throw new Error.Domain("_gsv"); } return environment.SystemVariables[name]; }
internal static AType GetSystemVariable(Aplus environment, AType input) { ATypes type = input.Type; if (type != ATypes.ASymbol && type != ATypes.AChar) { throw new Error.Type("_gsv"); } string name = (type == ATypes.ASymbol) ? input.asString : input.ToString(); if (!environment.SystemVariables.Contains(name)) { throw new Error.Domain("_gsv"); } return(environment.SystemVariables[name]); }
internal static AType Loadfile(Aplus environment, AType filename) { string fileName = filename.ToString(); if (filename.Type != ATypes.AChar) { throw new Error.Type("_loadfile"); } if (!File.Exists(fileName)) { throw new Error.Invalid("_loadfile"); } AType result = AArray.Create(ATypes.AChar); using (FileStream fileStream = new FileStream(fileName, FileMode.Open)) { int blockReadSize = 5 * 1024; // 5 KiB long totalSize = fileStream.Length; int readLength = blockReadSize < totalSize ? blockReadSize : (int)totalSize; byte[] filePartialContent = new byte[readLength]; int sum = 0; // total number of bytes read int count; // current number of bytes read // read until Read method returns 0 (end of the stream has been reached) while ((count = fileStream.Read(filePartialContent, 0, readLength)) > 0) { sum += count; // sum is a buffer offset for next reading // build the array from the bytes that was read for (int i = 0; i < count; i++) { result.Add(AChar.Create((char)filePartialContent[i])); } // calculate the next size of the read block long leftover = totalSize - sum; readLength = blockReadSize < leftover ? blockReadSize : (int)leftover; } return result; } }
public override AType Execute(AType right, AType left, Aplus environment) { // Environment is required! Assert.NotNull(environment); if (right.Type != ATypes.AChar) { throw new Error.Type(this.TypeErrorText); } if (right.Rank > 1) { throw new Error.Rank(this.RankErrorText); } string sourceCode = right.ToString(); AType result; if (left.Type == ATypes.ASymbol) { AType symbol; if (left.TryFirstScalar(out symbol)) { result = ExecuteWithContextSwitch(environment, sourceCode, symbol.asString); } else { result = ProtectedExecute(environment, sourceCode); } } else if (left.Type == ATypes.AInteger || left.Type == ATypes.ANull) { result = ProtectedExecute(environment, sourceCode); } else { throw new Error.Type(this.TypeErrorText); } return(result); }
public override AType Execute(AType right, AType left, Aplus environment) { // Environment is required! Assert.NotNull(environment); if (right.Type != ATypes.AChar) { throw new Error.Type(this.TypeErrorText); } if (right.Rank > 1) { throw new Error.Rank(this.RankErrorText); } string sourceCode = right.ToString(); AType result; if(left.Type == ATypes.ASymbol) { AType symbol; if(left.TryFirstScalar(out symbol)) { result = ExecuteWithContextSwitch(environment, sourceCode, symbol.asString); } else { result = ProtectedExecute(environment, sourceCode); } } else if (left.Type == ATypes.AInteger || left.Type == ATypes.ANull) { result = ProtectedExecute(environment, sourceCode); } else { throw new Error.Type(this.TypeErrorText); } return result; }
public static AType FileSize(Aplus environment, AType argument) { if (argument.Type != ATypes.AChar) { throw new Error.Type("sys.filesize"); } AType result; string fileName = argument.ToString(); if (File.Exists(fileName)) { result = Utils.CreateATypeResult((new FileInfo(fileName)).Length); } else { result = AInteger.Create(-1); } return(result); }
public static AType FileSize(Aplus environment, AType argument) { if (argument.Type != ATypes.AChar) { throw new Error.Type("sys.filesize"); } AType result; string fileName = argument.ToString(); if (File.Exists(fileName)) { result = Utils.CreateATypeResult((new FileInfo(fileName)).Length); } else { result = AInteger.Create(-1); } return result; }
private void ExecuteLabel_MouseUp(object sender, MouseButtonEventArgs e) { string code = this.codeBox.Text; ScriptRuntimeSetup setup = new ScriptRuntimeSetup(); setup.LanguageSetups.Add(AplusCore.Runtime.AplusLanguageContext.LanguageSetup); setup.Options.Add( new KeyValuePair <string, object>( "LexerMode", this.aplinput ? AplusCore.Compiler.LexerMode.APL : AplusCore.Compiler.LexerMode.ASCII ) ); ScriptRuntime dlrRuntime = new ScriptRuntime(setup); ScriptEngine engine = dlrRuntime.GetEngine(@"A+"); try { AType result = engine.Execute <AType>(code); this.ResultTextBox.Text = result.ToString(); } catch (Error error) { this.ResultTextBox.Text = error.ToString(); } catch (Exception ex) { this.ResultTextBox.Text = ex.Message; } if (!this.AnimatedExpander.IsExpanded) { this.AnimatedExpander.IsExpanded = true; ExpandOrCollapese(this.AnimatedExpander); } }
public override AType Execute(AType argument, Aplus environment) { // Environment is required! Assert.NotNull(environment); if (argument.Type != ATypes.AChar) { throw new Error.Type(this.TypeErrorText); } if (argument.Rank > 1) { throw new Error.Rank(this.RankErrorText); } DLR.Expression <Func <Aplus, AType> > lambda = BuildExecuteMethod(argument.ToString(), environment); Func <Aplus, AType> method = lambda.Compile(); AType result = method(environment); return(result); }
public override AType Execute(AType argument, Aplus environment) { // Environment is required! Assert.NotNull(environment); if (argument.Type != ATypes.AChar) { throw new Error.Type(this.TypeErrorText); } if (argument.Rank > 1) { throw new Error.Rank(this.RankErrorText); } DLR.Expression<Func<Aplus, AType>> lambda = BuildExecuteMethod(argument.ToString(), environment); Func<Aplus, AType> method = lambda.Compile(); AType result = method(environment); return result; }
protected override byte[] ConvertToByte(AType message) { if (message.Type != ATypes.AChar) { throw new ADAPException(ADAPExceptionType.Export); } byte[] result; try { result = ASCIIEncoder.GetBytes(message.ToString()); } catch (ArgumentNullException) { throw new ADAPException(ADAPExceptionType.Export); } catch (EncoderFallbackException) { throw new ADAPException(ADAPExceptionType.Export); } return(result); }
/// <summary> /// Writes data to the specified file. /// </summary> /// <param name="environment"></param> /// <param name="variableName"> /// The name of the variable which stores the data to write into the file. /// </param> /// <param name="filename">The filename to write the data to.</param> public static void WriteToFile(Aplus environment, string variableName, string filename) { AType data = null; try { data = Function.Monadic.MonadicFunctionInstance.Value.Execute(ASymbol.Create(variableName), environment); } catch (Error) { // intentionally left blank } if (data != null) { try { using (FileStream fileStream = new FileStream(filename, FileMode.Create)) { foreach (char item in data.ToString()) { fileStream.WriteByte((byte)item); } } } catch (ArgumentException) { throw new Error.Invalid("$>"); } } else { Console.WriteLine("bad varname"); } }
protected override byte[] ConvertToByte(AType message) { if (message.Type != ATypes.AChar) { throw new ADAPException(ADAPExceptionType.Export); } byte[] result; try { result = ASCIIEncoder.GetBytes(message.ToString()); } catch (ArgumentNullException) { throw new ADAPException(ADAPExceptionType.Export); } catch (EncoderFallbackException) { throw new ADAPException(ADAPExceptionType.Export); } return result; }
public static void Main(string[] args) { var argList = args.ToList(); var jsIdx = argList.FindIndex(c => c.Contains("-js")); var debug = argList.FindIndex(c => c.Contains("-d")) > -1; var runRepl = argList.FindIndex(c => c.Contains("-i")) > -1 || args.Length == 0; if (debug) { Debugger.Launch(); } if (args.Length > 0 && jsIdx > -1 && !runRepl) { int times = 1; var timeIdx = args.Take(jsIdx).ToList().FindIndex(c => c.Contains("-n")); if (timeIdx > -1) { times = int.Parse(args[timeIdx + 1]); } long kbAtExecution = GC.GetTotalMemory(false) / 1024; var watch = new Stopwatch(); var parser = new Parser(); watch.Start(); AType ret = null; var cmd = String.Join(" ", args.Skip(jsIdx + 1).ToArray()); Console.WriteLine(cmd); try { for (var i = 0; i < times; i++) { ret = parser.parse(cmd); } } catch (Exception e) { Console.WriteLine(e); } watch.Stop(); if (ret != null) { Console.WriteLine(ret.ToString()); } Console.WriteLine("Took: {0} ms", (watch.ElapsedMilliseconds) / (double)times); Console.WriteLine("Total: {0} ms", (watch.ElapsedMilliseconds)); long kbAfter1 = GC.GetTotalMemory(false) / 1024; long kbAfter2 = GC.GetTotalMemory(true) / 1024; Console.WriteLine(kbAtExecution + " Started with this kb."); Console.WriteLine(kbAfter1 + " After the test."); Console.WriteLine(kbAfter1 - kbAtExecution + " Amt. Added."); Console.WriteLine(kbAfter2 + " Amt. After Collection"); Console.WriteLine(kbAfter2 - kbAfter1 + " Amt. Collected by GC."); } else if (args.Length > 0 && args[0] == "-tp") { } else { var repl = new Parser(); MicroJ.Parser.MAX_DECIMAL = 6; var files = new List <string>(); if (File.Exists("stdlib.ijs")) { files.Add("stdlib.ijs"); } if (File.Exists("profile.ijs")) { files.Add("profile.ijs"); } if (File.Exists("..\\stdlib.ijs")) { files.Add("..\\stdlib.ijs"); } if (args.Length > 0) { files.AddRange(args); } bool testMode = argList.FindIndex(c => c.Contains("-t")) > -1; if (testMode) { new Tests().TestAll(); } foreach (var file in files.Where(x => !x.StartsWith("-"))) { if (!File.Exists(file) && !file.StartsWith("~")) { Console.WriteLine("file: " + file + " does not exist"); return; } testMode = argList.FindIndex(c => c.Contains("-t")) > -1; bool quiet = argList.FindIndex(c => c.Contains("-q")) > -1; if (file == "stdlib.ijs") { quiet = true; testMode = false; } string[] lines = null; if (!file.StartsWith("~")) { lines = File.ReadAllLines(file); } else { lines = new string[] { file.Substring(1) } }; for (var i = 0; i < lines.Length; i++) { var line = lines[i]; try { if (line.StartsWith("NB.") || line.TrimStart(new char[] { ' ', '\t' }).Length == 0) { continue; } if (line.StartsWith("exit")) { break; } if (line.StartsWith("!B")) { Debugger.Launch(); Debugger.Break(); line = line.Substring(2, line.Length - 2); } repl.ReadLine = () => { i++; return(lines[i]); }; var ret = repl.parse(line).ToString(); if (testMode && ret != "1" && !line.EndsWith("3 : 0") && !line.EndsWith("4 : 0")) { var eqIdx = line.IndexOf("="); var rerun = ""; if (eqIdx > -1) { rerun = repl.parse(line.Substring(0, eqIdx)).ToString(); } eqIdx = line.IndexOf("-:"); if (eqIdx > -1) { rerun = repl.parse(line.Substring(0, eqIdx)).ToString(); } Console.WriteLine("TEST FAILED - " + line + " returned " + ret + " output: " + rerun); } if (!quiet) { Console.WriteLine(ret); } } catch (Exception e) { Console.WriteLine(line + "\n" + e); //if (Parser.ThrowError) { throw; } break; } } } if (runRepl) { string prompt = " "; bool hasError = false; while (true || hasError) { Console.Write(prompt); repl.ReadLine = Console.ReadLine; var line = Console.ReadLine(); if (line == null) { break; } // on Linux, pressing arrow keys will insert null characters to line line = line.Replace("\0", ""); if (line == "exit") { break; } line = line.Trim(); if (line == "") { continue; } try { var ret = repl.parse(line); if (ret.GetCount() > 1000) { var formatter = new Formatter(ret.Shape); for (var i = 0; i < ret.GetCount() && i < 1000; i++) { formatter.Add(ret.GetString(i)); } Console.WriteLine(formatter.ToString()); } else { Console.WriteLine(ret.ToString()); } } catch (Exception e) { Console.WriteLine(e.ToString()); hasError = true; } } } } } }