Object CalcSimpleExpression(String expression) { var lexpr = DynamicParser.ParseLambda(null, expression); var lambda = lexpr.Compile(); return(lambda.DynamicInvoke()); }
public T CalcExpression <T>(ExpandoObject root, String expression) { Object result; if (_lambdas != null && _lambdas.TryGetValue(expression, out Delegate expr)) { result = expr.DynamicInvoke(root); } else { if (_lambdas == null) { _lambdas = new Dictionary <String, Delegate>(); } var prms = new ParameterExpression[] { Expression.Parameter(typeof(ExpandoObject), "Root") }; var lexpr = DynamicParser.ParseLambda(prms, expression); expr = lexpr.Compile(); _lambdas.Add(expression, expr); result = expr.DynamicInvoke(root); } if (result == null) { return(default);
Object CalcExpression(String expression, String prm, Object value) { var prms = new ParameterExpression[] { Expression.Parameter(typeof(Object), prm) }; var lexpr = DynamicParser.ParseLambda(prms, expression); var lambda = lexpr.Compile(); return(lambda.DynamicInvoke(value)); }
public Downloader(List <string> files, Settings settings, CancellationToken cancelToken) { _files = files; _settings = settings; _cancelToken = cancelToken; TotalFiles = files.Count; ProcessingFiles = new ConcurrentDictionary <string, ProcessingFileInfo>(); Errors = new ConcurrentBag <DownloadError>(); _matchRanker = new MatchRanker(settings.MinSimilarity, settings.Services); _parser = new DynamicParser(); }
private WaebricParser() { //Load grammar and initialize parser and graphbuilder String grammarPath = Path.GetDirectoryName(Assembly.GetAssembly(typeof(WaebricParser)).CodeBase); grammarPath += "\\Waebric.mx"; grammarPath = grammarPath.Substring(6); Grammar = new MImage(grammarPath); Parser = Grammar.ParserFactories["Waebric.Waebric"].Create(); Parser.GraphBuilder = new NodeGraphBuilder(); }
public static IContainer GenerateContainer(ILog logger) { if (_testContainer != null) { return(_testContainer); } if (logger == null) { logger = new NoOpLog(); } var headerParser = new FileHeaderParser(logger); var trailerParser = new FileTrailerParser(); var nameParser = new CosNameParser(); var dictionaryParser = new CosDictionaryParser(nameParser, logger); var baseParser = new CosBaseParser(nameParser, new CosStringParser(), dictionaryParser, new CosArrayParser()); var streamParser = new CosStreamParser(logger); var filterProvider = new MemoryFilterProvider(new DecodeParameterResolver(logger), new PngPredictor(), logger); var crossReferenceParser = new CrossReferenceStreamParser(filterProvider); var objectStreamParser = new ObjectStreamParser(logger, filterProvider, baseParser); var dynamicParser = new DynamicParser(logger, baseParser, streamParser, objectStreamParser); var crossReferenceTableParser = new CrossReferenceParser(logger, dictionaryParser, baseParser, streamParser, crossReferenceParser, new CrossReferenceTableParser(), new OldCrossReferenceTableParser(logger, dictionaryParser, baseParser)); var cmapParser = new CMapParser(); var afmParser = new AdobeFontMetricsParser(); var container = new Container(); container.Register(headerParser); container.Register(trailerParser); container.Register(nameParser); container.Register(dictionaryParser); container.Register(baseParser); container.Register(streamParser); container.Register(crossReferenceParser); container.Register(crossReferenceTableParser); container.Register(dynamicParser); container.Register(objectStreamParser); container.Register(filterProvider); container.Register(cmapParser); container.Register(afmParser); container.Register(logger); return(container); }
/// <summary> /// Returns a new core command that when executed materializes the operation this instance /// refers to, or null if that command cannot be generated for any reasons. /// </summary> /// <returns>A new core command, or null.</returns> public IQueryCommand GenerateCoreCommand() { var cmd = _Template == null ? null : _Template.Clone(); if (cmd != null) { var name = Map.Table; if (_MasterAlias != null) { name = string.Format("{0} AS {1}", name, _MasterAlias); } cmd.From(x => name); foreach (var entry in Map.Schema) { name = entry.ColumnName; if (_MasterAlias != null) { name = string.Format("{0}.{1}", _MasterAlias, name); } cmd.Select(x => name); } if (Map.Discriminator != null) { if (_MasterAlias == null) { cmd.Where(Map.Discriminator); } else { var parser = DynamicParser.Parse(Map.Discriminator); var result = parser.Result; var host = new DynamicNode.GetMember( new DynamicNode.Argument(parser.DynamicArguments.First().Name), _MasterAlias); MasterVisitor(host, (DynamicNode)result); cmd.Where(x => parser.Result); } } } return(cmd); }
public T CalcExpression <T>(ExpandoObject root, String expression) { Object result = null; if (_lambdas != null && _lambdas.TryGetValue(expression, out Delegate expr)) { result = expr.DynamicInvoke(root); } else { if (_lambdas == null) { _lambdas = new Dictionary <String, Delegate>(); } var prms = new ParameterExpression[] { Expression.Parameter(typeof(ExpandoObject), "Root") }; var lexpr = DynamicParser.ParseLambda(prms, expression); expr = lexpr.Compile(); _lambdas.Add(expression, expr); result = expr.DynamicInvoke(root); } if (result == null) { return(default(T)); } if (result is T resultT) { return(resultT); } var tp = typeof(T); if (tp.IsNullableType()) { tp = Nullable.GetUnderlyingType(tp); } return((T)Convert.ChangeType(result, tp)); }
/// <summary> /// Defines the names and values of the columns affected by this command, or adds the new /// ones to any previous one that may exist. /// </summary> /// <param name="columns">A collection of dynamic lambda expressions resolving into the /// column and values affected by this command using a 'x => x.Column = Value' syntax, /// where the value part can be any valid SQL sentence.</param> /// <returns>A self-reference to permit a fluent syntax chaining.</returns> public IUpdateCommand Columns(params Func <dynamic, object>[] columns) { if (IsDisposed) { throw new ObjectDisposedException(this.ToString()); } if (columns == null) { throw new ArgumentNullException("columns", "Array of specifications cannot be null."); } for (int i = 0; i < columns.Length; i++) { string main = null; string value = null; var parser = DynamicParser.Parse(columns[i]); var result = parser.Result; if (result == null) { throw new ArgumentException( "Expression #{0} '{1}' cannot resolve to null.".FormatWith(i, parser)); } while (true) { if (result is string) { var node = ((string)result).Trim(); var parts = node.Split('='); if (parts.Length < 2) { throw new ArgumentException( "Specification #{0} contains no '=' symabol while parsing '{1}'.".FormatWith(i, parser)); } main = parts[0].Trim(); value = parts[1].Trim(); break; } if (result is DynamicNode.SetMember) { var node = (DynamicNode.SetMember)result; var host = Link.Engine.Parser.Parse(node.Host); main = host == null ? node.Name : "{0}.{1}".FormatWith(host, node.Name); value = Link.Engine.Parser.Parse(node.Value, Parameters); break; } if (result is DynamicNode.Binary) { var node = (DynamicNode.Binary)result; if (node.Operation == ExpressionType.Equal) { main = Link.Engine.Parser.Parse(node.Left); value = Link.Engine.Parser.Parse(node.Right, Parameters); break; } } throw new ArgumentException( "Invalid column specification while parsing #{0} '{1}'.".FormatWith(i, parser)); } main = main.Validated("Column"); value = value.Validated("Value"); var str = "{0} = {1}".FormatWith(main, value); TheDataColumns = TheDataColumns == null ? str : "{0}, {1}".FormatWith(TheDataColumns, str); parser.Dispose(); } return(this); }
/// <summary> /// Defines the contents of the WHERE clause or append the new ones to any previous /// specification. /// <para>By default if any previous contents exist the new ones are appended using an AND /// operator. However, the virtual extension methods 'x => x.And(...)' and 'x => x.Or(...)' /// can be used to specify what logical operator to use.</para> /// </summary> /// <param name="where">The dynamic lambda expression that resolves into the contents of /// this clause.</param> /// <returns>A self-reference to permit a fluent syntax chaining.</returns> public IUpdateCommand Where(Func <dynamic, object> where) { if (IsDisposed) { throw new ObjectDisposedException(this.ToString()); } if (where == null) { throw new ArgumentNullException("where", "Specification cannot be null."); } string main = null; bool and = true; var parser = DynamicParser.Parse(where); var result = parser.Result; if (result == null) { throw new ArgumentException( "Expression '{0}' cannot resolve to null.".FormatWith(parser)); } while (true) { if (result is string) { main = ((string)result).Trim(); if (main.ToUpper().IndexOf("OR ") == 0) { and = false; main = main.Substring(3); } if (main.ToUpper().IndexOf("AND ") == 0) { and = true; main = main.Substring(4); } break; } if (result is DynamicNode.Method) { var node = (DynamicNode.Method)result; var name = node.Name.ToUpper(); if ((name == "AND" || name == "OR") && (node.Host is DynamicNode.Argument)) { if (node.Arguments == null) { throw new ArgumentException("Virtual method '{0}()' cannot be parameterless while parsing '{0}'.".FormatWith(name, parser)); } if (node.Arguments.Length != 1) { throw new ArgumentException("Virtual method '{0}()' can only have one argument while parsing '{0}'.".FormatWith(name, parser)); } if (node.Arguments[0] == null) { throw new ArgumentException("Argument of virtual method '{0}()' cannot be null while parsing '{0}'.".FormatWith(name, parser)); } and = (name == "AND"); result = node.Arguments[0]; } } main = Link.Engine.Parser.Parse(result, pc: Parameters); break; } main = main.Validated("Where"); if (TheWhereData == null) { TheWhereData = main; } else { TheWhereData = "{0} {1} {2}".FormatWith(TheWhereData, and ? "AND" : "OR", main); } parser.Dispose(); return(this); }
public ToDoLanguageServiceItem(BufferView b, ISquiggleProviderFactory squiggleProviderFactory) { this.bufferView = b; this.uri = this.bufferView.Buffer.Uri; this.squiggleProviderFactory = squiggleProviderFactory; this.squiggles = new List<ISquiggleAdornment>(); this.textBuffer = this.bufferView.TextBuffer; this.reparseTimer = new Timer(Reparse, null, Timeout.Infinite, Timeout.Infinite); // Described in MGrammar in a Nutshell (http://msdn.microsoft.com/en-us/library/dd129870.aspx) // and in PDC 2008 talk "Building Textual DSLs with the "Oslo" Modeling Language" (32:00 mark). // this.parser = null; using (Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("ToDo.mgx")) { // Load image and instantiate a corresponding dynamic parser this.parser = DynamicParser.LoadFromMgx(stream, "ToDo.Tasks4"); } this.classifier = new ParserClassifier(parser, bufferView.Buffer.TextBuffer); this.bufferView.EditorInitialized += OnBufferViewEditorInitialized; this.textBuffer.Changed += (ignore1, ignore2) => { lock (l) { bufferDirty = true; } }; }
/// <summary> /// Parses the given object, including any arbitrary command logic expressed as a /// dynamic lambda expression, and returns an string that can be understood by the /// underlying database engine. /// </summary> /// <param name="obj">The object to parse. It can be any object or reference, including /// null ones and dynamic lambda expressions.</param> /// <param name="pc">If not null the collection of parameters where to place the ones /// extracted from the object to parse. If null their string representation is used /// instead.</param> /// <param name="nulls">If true null references are accepted. Otherwise an exception is /// thrown.</param> /// <returns>A string contained the parsed input in a syntax that can be understood by /// the underlying database engine.</returns> public string Parse(object obj, IParameterCollection pc = null, bool nulls = true) { if (IsDisposed) { throw new ObjectDisposedException(this.ToString()); } DynamicParser parser = null; Func <string> dispatch = () => { if (obj != null) { if (obj is Delegate) { parser = DynamicParser.Parse((Delegate)obj); obj = parser.Result; } } if (obj != null) { if (obj is ICoreCommandProvider) { return(OnParseCoreCommandProvider((ICoreCommandProvider)obj, pc, nulls)); } if (obj is ICommand) { return(OnParseCommand((ICommand)obj, pc, nulls)); } if (obj is DynamicNode.Argument) { return(OnParseArgument((DynamicNode.Argument)obj)); } if (obj is DynamicNode.GetMember) { return(OnParseGetMember((DynamicNode.GetMember)obj, pc, nulls)); } if (obj is DynamicNode.GetIndexed) { return(OnParseGetIndexedMember((DynamicNode.GetIndexed)obj, pc, nulls)); } if (obj is DynamicNode.SetMember) { return(OnParseSetMember((DynamicNode.SetMember)obj, pc, nulls)); } if (obj is DynamicNode.SetIndexed) { return(OnParseSetIndexedMember((DynamicNode.SetIndexed)obj, pc, nulls)); } if (obj is DynamicNode.Unary) { return(OnParseUnary((DynamicNode.Unary)obj, pc, nulls)); } if (obj is DynamicNode.Binary) { return(OnParseBinary((DynamicNode.Binary)obj, pc, nulls)); } if (obj is DynamicNode.Method) { return(OnParseMethod((DynamicNode.Method)obj, pc, nulls)); } if (obj is DynamicNode.Invoke) { return(OnParseInvoke((DynamicNode.Invoke)obj, pc, nulls)); } if (obj is DynamicNode.Convert) { return(OnParseConvert((DynamicNode.Convert)obj, pc, nulls)); } } return(OnParseConstant(obj, pc)); }; if (obj == null && !nulls) { throw new ArgumentNullException("obj", "Null nodes are not accepted."); } var str = dispatch(); if (parser != null) { parser.Dispose(); } return(str); }
public Plugin(Logger logger, DynamicParser parser) { Logger = logger; Parser = parser; logger.Debug($"Initialized with {Parser}"); }
public void Initialize(string config) { // update proxy settings cap.ProxyAddress = Config.Local.ProxyAddress; cap.UseProxy = Config.Local.UseProxy; // get config directory path string path = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + @"\OptionsOracle\"; string conf = path + PARSER_FILE; // check if config directory exist, if not create it if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } // load / create-new configuration if (File.Exists(conf)) { try { // load xml from local configuration file xd.Load(conf); // initialize dynamic parser helper class dp = new DynamicParser(xd); if (RemoteConfig.CompareVersions(Config.Remote.GetLatestRemoteModuleVersion("parser"), dp.GetParserVersion()) == 1) { // newer parser file is available online, get it XmlDocument xd_online = cap.DownloadXmlWebFile(Config.Remote.GetRemoteModuleUrl("parser")); if (xd_online != null) { // update global xml file with latest one xd = xd_online; // save local xml document XmlWriterSettings wr_settings = new XmlWriterSettings(); wr_settings.Indent = true; XmlWriter wr = XmlWriter.Create(conf, wr_settings); xd.Save(wr); // recreate dynamic parser helper class with new xml file dp = new DynamicParser(xd); } } } catch { xd = new XmlDocument(); } } if (xd.FirstChild == null) { try { // get online xml document xd = cap.DownloadXmlWebFile(Config.Remote.GetRemoteModuleUrl("parser")); if (xd != null && xd.FirstChild != null) { // save local xml document XmlWriterSettings wr_settings = new XmlWriterSettings(); wr_settings.Indent = true; XmlWriter wr = XmlWriter.Create(conf, wr_settings); xd.Save(wr); // initialize dynamic parser helper class dp = new DynamicParser(xd); } else { dp = null; } } catch { } } }
public void LoadGrammar() { var errorReporter = ErrorReporter.Standard; Grammar = Settings.MGrammar; var compiler = new MGrammarCompiler { SourceItems = new[] { new SourceItem { Name = TestFileName ?? "Preview", ContentType = ContentType.Mg, TextReader = new StringReader(Grammar) } } }; if (compiler.Compile(errorReporter) != 0 || errorReporter.HasErrors) { compiler = null; return; } var dynamicParser = new DynamicParser(); compiler.LoadDynamicParser(dynamicParser); _parser = dynamicParser; }
/// <summary> /// Creates a new record parsing the collection of dynamic lambda expressions provided, /// each with the 'x => x.Table.Column = Value' or 'x => x.Column = Value' forms. /// <para>The new record carries its own ad-hoc schema and clones of the values given.</para> /// </summary> /// <param name="caseSensitiveNames">Whether the table and column names of the schema of /// the new record are case sensitive or not.</param> /// <param name="specs">The collectoin of dynamic lambda expressions that specify the /// contents and schema of the new record.</param> /// <returns>A new record.</returns> public static IRecord Create(bool caseSensitiveNames, params Func <dynamic, object>[] specs) { if (specs == null) { throw new ArgumentNullException("specs", "List of specifications cannot be null."); } if (specs.Length == 0) { throw new ArgumentException("List of specifications cannot be empty."); } var builder = new RecordBuilder(caseSensitiveNames); for (int i = 0; i < specs.Length; i++) { var spec = specs[i]; if (spec == null) { throw new ArgumentNullException("Specification #{0} cannot be null.".FormatWith(i)); } var parser = DynamicParser.Parse(spec); var result = parser.Result; if (result == null) { throw new ArgumentNullException("Specification #{0}: '{1}' cannot resolve to null.".FormatWith(i, parser)); } if (result is DynamicNode.SetMember) // The assignation syntax... { var node = (DynamicNode.SetMember)result; if (node.Host is DynamicNode.Argument) // x.Column = value; { builder[node.Name] = node.Value; continue; } if (node.Host is DynamicNode.GetMember) // x.Table.Column = value; { var host = (DynamicNode.GetMember)node.Host; builder[host.Name, node.Name] = node.Value; continue; } } if (result is DynamicNode.Binary) { var node = (DynamicNode.Binary)result; if (node.Operation == ExpressionType.Equal) { var host = (DynamicNode.GetMember)node.Left; if (host.Host is DynamicNode.Argument) // x.Column == value; { builder[host.Name] = node.Right; continue; } if (host.Host is DynamicNode.GetMember) // x.Table.Column == value; { var member = (DynamicNode.GetMember)host.Host; if (member.Host is DynamicNode.Argument) { builder[member.Name, host.Name] = node.Right; continue; } } } } throw new ArgumentException("Specification #{0}: '{1}' is invalid.".FormatWith(i, parser)); } var record = builder.Create(); builder.Dispose(); return(record); }