Exemple #1
0
        protected override bool Run()
        {
            if (input == null)
            {
                Computation input_lookup = new Lookup(task_master, source_reference, new [] { "arg" }, context);
                input_lookup.Notify(input_result => {
                    if (input_result is Stringish)
                    {
                        input = input_result.ToString();
                        if (Interlocked.Decrement(ref interlock) == 0)
                        {
                            task_master.Slot(this);
                        }
                    }
                    else
                    {
                        task_master.ReportOtherError(source_reference, "Input argument must be a string.");
                    }
                });

                if (Interlocked.Decrement(ref interlock) > 0)
                {
                    return(false);
                }
            }
            var frame = new MutableFrame(task_master, source_reference, context, container);

            for (int it = 0; it < input.Length; it++)
            {
                frame.Set(it + 1, (long)Char.ConvertToUtf32(input, it));
            }
            result = frame;
            return(true);
        }
        protected override bool Run()
        {
            if (!state)
            {
                var input_lookup = new Lookup(task_master, source_ref, new [] { "args" }, context);
                input_lookup.Notify(HandleArgs);
                var transformation_lookup = new Lookup(task_master, source_ref, new [] { "transformations" }, context);
                transformation_lookup.Notify(HandleTransformations);
                state = true;
                if (Interlocked.Decrement(ref interlock) > 0)
                {
                    return(false);
                }
            }
            var output_frame = new MutableFrame(task_master, source_ref, context, self);

            foreach (var entry in input)
            {
                var in_str = entry.Value;
                var buffer = new StringBuilder();
                for (var it = 0; it < in_str.Length; it += Char.IsSurrogatePair(in_str, it) ? 2 : 1)
                {
                    var    c            = Char.ConvertToUtf32(in_str, it);
                    var    is_surrogate = Char.IsSurrogatePair(in_str, it);
                    string replacement;
                    if (single_substitutions.TryGetValue(c, out replacement))
                    {
                        buffer.Append(replacement);
                    }
                    else
                    {
                        bool matched = false;
                        foreach (var range in ranges.Values)
                        {
                            if (c >= range.start && c <= range.end)
                            {
                                var utf8 = new byte[4];

                                Encoding.UTF8.GetBytes(in_str, it, is_surrogate ? 2 : 1, utf8, 0);
                                buffer.Append(String.Format(range.replacement, c, (int)in_str[it], is_surrogate ? (int)in_str[it + 1] : 0, (int)utf8[0], (int)utf8[1], (int)utf8[2], (int)utf8[3]));
                                matched = true;
                                break;
                            }
                        }
                        if (!matched)
                        {
                            buffer.Append(Char.ConvertFromUtf32(c));
                        }
                    }
                }
                output_frame.Set(entry.Key, new SimpleStringish(buffer.ToString()));
            }
            result = output_frame;
            return(true);
        }
Exemple #3
0
        public static Frame Through(TaskMaster task_master, SourceReference source_ref, long start, long end,
                                    Context context, Frame container)
        {
            var result = new MutableFrame(task_master, source_ref, context, container);

            if (end < start)
            {
                return(result);
            }
            for (long it = 0; it <= (end - start); it++)
            {
                result.Set(TaskMaster.OrdinalNameStr(it + 1), start + it);
            }
            return(result);
        }
Exemple #4
0
        protected override bool Run()
        {
            if (mappings.Count == 0)
            {
                interlock = categories.Count + 2;
                Computation input_lookup = new Lookup(task_master, source_reference, new [] { "arg" }, context);
                input_lookup.Notify(input_result => {
                    if (input_result is Stringish)
                    {
                        input = input_result.ToString();
                        if (Interlocked.Decrement(ref interlock) == 0)
                        {
                            task_master.Slot(this);
                        }
                    }
                    else
                    {
                        task_master.ReportOtherError(source_reference, "Input argument must be a string.");
                    }
                });

                foreach (var entry in categories)
                {
                    var lookup = new Lookup(task_master, source_reference, new [] { entry.Value }, context);
                    lookup.Notify(cat_result => {
                        mappings[entry.Key] = cat_result;
                        if (Interlocked.Decrement(ref interlock) == 0)
                        {
                            task_master.Slot(this);
                        }
                    });
                }

                if (Interlocked.Decrement(ref interlock) > 0)
                {
                    return(false);
                }
            }
            var frame = new MutableFrame(task_master, source_reference, context, container);

            for (int it = 0; it < input.Length; it++)
            {
                frame.Set(it + 1, mappings[Char.GetUnicodeCategory(input[it])]);
            }
            result = frame;
            return(true);
        }
        protected override bool Run()
        {
            if (tmpl == null)
            {
                new Lookup(task_master, src_ref, names, context).Notify(tmpl_result => {
                    if (tmpl_result is Template)
                    {
                        tmpl = (Template)tmpl_result;
                        if (Interlocked.Decrement(ref interlock) == 0)
                        {
                            task_master.Slot(this);
                        }
                    }
                    else
                    {
                        task_master.ReportOtherError(src_ref, string.Format("Expected “{0}” to be a Template but got {1}.", string.Join(".", names), Stringish.NameForType(tmpl_result.GetType())));
                    }
                });
                if (Interlocked.Decrement(ref interlock) > 0)
                {
                    return(false);
                }
            }
            var frame = new MutableFrame(task_master, new JunctionReference("instantiation", "<native>", 0, 0, 0, 0, src_ref, tmpl.SourceReference), Context.Append(context, tmpl.Context), container);

            foreach (var entry in overrides)
            {
                frame.Set(entry.Key, entry.Value);
            }
            foreach (var name in tmpl.GetAttributeNames())
            {
                if (!overrides.ContainsKey(name))
                {
                    frame.Set(name, tmpl[name]);
                }
            }
            result = frame;
            return(true);
        }
Exemple #6
0
        public static int Main(string[] args)
        {
            var show_help       = false;
            var use_precompiled = true;
            var options         = new OptionSet {
                { "p|no-precomp", "do not use precompiled libraries", v => use_precompiled = v == null },
                { "h|help", "show this message and exit", v => show_help = v != null }
            };

            List <string> files;

            try {
                files = options.Parse(args);
            } catch (OptionException e) {
                Console.Error.Write(AppDomain.CurrentDomain.FriendlyName + ": ");
                Console.Error.WriteLine(e.Message);
                Console.Error.WriteLine("Try “" + AppDomain.CurrentDomain.FriendlyName + " --help” for more information.");
                return(1);
            }

            if (show_help)
            {
                Console.WriteLine("Usage: " + AppDomain.CurrentDomain.FriendlyName + " input.o_0");
                Console.WriteLine("Run Flabbergast interactively.");
                Console.WriteLine();
                Console.WriteLine("Options:");
                options.WriteOptionDescriptions(Console.Out);
                return(1);
            }

            if (files.Count > 1)
            {
                Console.Error.WriteLine("No more than one Flabbergast script may be given.");
                return(1);
            }

            Frame original = null;

            var assembly_builder = AppDomain.CurrentDomain.DefineDynamicAssembly(new AssemblyName("Repl"), AssemblyBuilderAccess.Run);
            var module_builder   = assembly_builder.DefineDynamicModule("ReplModule");
            var unit             = new CompilationUnit(module_builder, false);
            var collector        = new ConsoleCollector();
            var task_master      = new ConsoleTaskMaster();

            task_master.AddUriHandler(new CurrentInformation(true));
            task_master.AddUriHandler(BuiltInLibraries.INSTANCE);
            task_master.AddUriHandler(SettingsHandler.INSTANCE);
            task_master.AddUriHandler(EnvironmentUriHandler.INSTANCE);
            task_master.AddUriHandler(HttpHandler.INSTANCE);
            task_master.AddUriHandler(FtpHandler.INSTANCE);
            task_master.AddUriHandler(FileHandler.INSTANCE);
            var resource_finder = new ResourcePathFinder();

            resource_finder.PrependPath(Path.Combine(files.Count == 1 ? Path.GetDirectoryName(Path.GetFullPath(files[0])) : Environment.CurrentDirectory, "lib"));
            resource_finder.AddDefault();
            var db_handler = new DbUriHandler();

            db_handler.Finder = resource_finder;
            task_master.AddUriHandler(db_handler);
            var resource_handler = new ResourceHandler();

            resource_handler.Finder = resource_finder;
            task_master.AddUriHandler(resource_handler);
            if (use_precompiled)
            {
                var precomp = new LoadPrecompiledLibraries();
                precomp.Finder = resource_finder;
                task_master.AddUriHandler(precomp);
            }
            var dyncomp = new DynamicallyCompiledLibraries(collector);

            dyncomp.Finder = resource_finder;
            task_master.AddUriHandler(dyncomp);

            if (files.Count == 1)
            {
                var parser    = Parser.Open(files[0]);
                var root_type = parser.ParseFile(collector, unit, "REPLRoot");
                if (root_type != null)
                {
                    var computation = (Computation)Activator.CreateInstance(root_type, task_master);
                    computation.Notify(r => original = r as Frame);
                    task_master.Run();
                    task_master.ReportCircularEvaluation();
                }
            }
            if (original == null)
            {
                original = new MutableFrame(task_master, new NativeSourceReference("REPL"), null, null);
            }

            var           id             = 0;
            Frame         current        = original;
            bool          run            = true;
            ConsumeResult update_current = (x) => current = (x as Frame) ?? current;

            var line_editor  = new LineEditor("flabbergast");
            var completables = new Completables();

            line_editor.AutoCompleteEvent = completables.Handler;
            string s;

            while (run && (s = line_editor.Edit(id + "‽ ", "")) != null)
            {
                if (string.IsNullOrWhiteSpace(s))
                {
                    continue;
                }
                var parser   = new Parser("line" + id, s);
                var run_type = parser.ParseRepl(collector, unit, "REPL" + id++);
                if (run_type != null)
                {
                    object result      = null;
                    var    computation = (Computation)Activator.CreateInstance(run_type, new object[] { task_master, original, current, update_current, (ConsumeResult)(output => result = output), (ConsumeResult)Console.WriteLine });
                    computation.Notify(r => run = (r as bool?) ?? true);
                    task_master.Run();
                    if (result != null)
                    {
                        HandleResult(result);
                    }
                    task_master.ReportCircularEvaluation();
                }
            }
            line_editor.SaveHistory();
            return(0);
        }
Exemple #7
0
        internal static ComputeValue Dispatch(object name, JsonValue node)
        {
            return((TaskMaster task_master, SourceReference source_ref, Context context, Frame self, Frame container) => {
                if (node == null)
                {
                    return new Instantiation(task_master, source_ref, context, self, "json", "scalar")
                    {
                        { "json_name", name }, { "arg", Unit.NULL }
                    };
                }
                switch (node.JsonType)
                {
                case JsonType.Array:
                    return new Instantiation(task_master, source_ref, context, self, "json", "list")
                    {
                        { "json_name", name }, { "children",
                                                 (ComputeValue)((TaskMaster a_task_master, SourceReference a_reference, Context a_context, Frame a_self, Frame a_container) => {
                                var a_arg_frame = new MutableFrame(a_task_master, a_reference, a_context, a_self);
                                var index = 1;
                                foreach (var item in (JsonArray)node)
                                {
                                    a_arg_frame.Set(index, Dispatch(Unit.NULL, item));
                                    index++;
                                }
                                return new Precomputation(a_arg_frame);
                            }) }
                    };

                case JsonType.Boolean:
                    return new Instantiation(task_master, source_ref, context, self, "json", "scalar")
                    {
                        { "json_name", name }, { "arg", (bool)node }
                    };

                case JsonType.Number:
                    return new Instantiation(task_master, source_ref, context, self, "json", "scalar")
                    {
                        { "json_name", name }, { "arg", (double)node }
                    };

                case JsonType.Object:
                    return new Instantiation(task_master, source_ref, context, self, "json", "object")
                    {
                        { "json_name", name }, { "children",
                                                 (ComputeValue)((TaskMaster o_task_master, SourceReference o_reference, Context o_context, Frame o_self, Frame o_container) => {
                                var o_arg_frame = new MutableFrame(o_task_master, o_reference, o_context, o_self);
                                var index = 1;
                                foreach (var entry in (JsonObject)node)
                                {
                                    o_arg_frame.Set(index, Dispatch(new SimpleStringish(entry.Key), entry.Value));
                                    index++;
                                }
                                return new Precomputation(o_arg_frame);
                            }) }
                    };

                case JsonType.String:
                    return new Instantiation(task_master, source_ref, context, self, "json", "scalar")
                    {
                        { "json_name", name }, { "arg", new SimpleStringish((string)node) }
                    };

                default:
                    return new FailureComputation(task_master, source_ref, "Unknown JSON entry.");
                }
            });
        }
Exemple #8
0
        protected override bool Run()
        {
            if (connection == null)
            {
                new Lookup(task_master, source_ref, new [] { "connection" },
                           context).Notify(return_value => {
                    if (return_value is ReflectedFrame)
                    {
                        Object backing = ((ReflectedFrame)return_value).Backing;
                        if (backing is DbConnection)
                        {
                            connection = (DbConnection)backing;
                            if (Interlocked.Decrement(ref interlock) == 0)
                            {
                                task_master.Slot(this);
                            }
                            return;
                        }
                    }
                    task_master
                    .ReportOtherError(source_ref,
                                      "Expected “connection” to come from “sql:” import.");
                });
                new Lookup(task_master, source_ref, new [] { "sql_query" },
                           context).Notify(return_value => {
                    if (return_value is Stringish)
                    {
                        query = return_value.ToString();
                        if (Interlocked.Decrement(ref interlock) == 0)
                        {
                            task_master.Slot(this);
                        }
                        return;
                    }
                    task_master.ReportOtherError(source_ref, string.Format(
                                                     "Expected type Str for “sql_query”, but got {0}.",
                                                     Stringish.NameForType(return_value.GetType())));
                });
                new Lookup(task_master, source_ref, new [] { "sql_row_tmpl" },
                           context).Notify(return_value => {
                    if (return_value is Template)
                    {
                        row_tmpl = (Template)return_value;
                        if (Interlocked.Decrement(ref interlock) == 0)
                        {
                            task_master.Slot(this);
                        }
                        return;
                    }
                    task_master.ReportOtherError(source_ref, string.Format(
                                                     "Expected type Template for “sql_row_tmpl”, but got {0}.",
                                                     Stringish.NameForType(return_value.GetType())));
                });
                if (Interlocked.Decrement(ref interlock) > 0)
                {
                    return(false);
                }
            }
            try {
                var command = connection.CreateCommand();
                command.CommandType = System.Data.CommandType.Text;
                command.CommandText = query;
                var reader = command.ExecuteReader();
                if (debug)
                {
                    Console.WriteLine("SQL Query to {0}: {1}", connection, query);
                }
                NameChooser name_chooser = (rs, it) => TaskMaster.OrdinalNameStr(it);
                var         retrievers   = new List <Retriever>();
                for (int col = 0; col < reader.FieldCount; col++)
                {
                    var column = col;
                    if (reader.GetName(col) == "ATTRNAME")
                    {
                        name_chooser = (rs, it) => rs.GetString(column);
                        continue;
                    }
                    if (reader.GetName(col).StartsWith("$"))
                    {
                        var attr_name = reader.GetName(col).Substring(1);
                        if (!task_master.VerifySymbol(source_ref, attr_name))
                        {
                            return(false);
                        }
                        retrievers.Add((rs, frame, _task_master) => frame.Set(attr_name, rs.IsDBNull(column) ? Precomputation.Capture(Unit.NULL) : Lookup.Do(rs.GetString(column).Split('.'))));
                        continue;
                    }
                    Unpacker unpacker;
                    if (!unpackers.TryGetValue(reader.GetFieldType(col), out unpacker))
                    {
                        task_master
                        .ReportOtherError(
                            source_ref,
                            string.Format(
                                "Cannot convert SQL type “{0}” for column “{1}” into Flabbergast type.",
                                reader.GetFieldType(col),
                                reader.GetName(col)));
                    }
                    if (!task_master.VerifySymbol(source_ref,
                                                  reader.GetName(col)))
                    {
                        return(false);
                    }
                    retrievers.Add(Bind(reader.GetName(col), col, unpacker));
                }

                var list = new MutableFrame(task_master, source_ref, context, self);
                for (int it = 1; reader.Read(); it++)
                {
                    var frame = new MutableFrame(task_master, new JunctionReference(string.Format("SQL template instantiation row {0}", it), "<sql>", 0, 0, 0, 0, source_ref, row_tmpl.SourceReference), Context.Append(list.Context, row_tmpl.Context), list);
                    foreach (var r in retrievers)
                    {
                        r(reader, frame, task_master);
                    }
                    foreach (var name in row_tmpl.GetAttributeNames())
                    {
                        if (!frame.Has(name))
                        {
                            frame.Set(name, row_tmpl[name]);
                        }
                    }
                    list.Set(name_chooser(reader, it), frame);
                }
                list.Slot();
                result = list;
                return(true);
            } catch (DataException e) {
                task_master.ReportOtherError(source_ref, e.Message);
                return(false);
            }
        }