public void Setup()
		{
			ccu = new CodeCompileUnit();
			mocks = new MockRepository();
			engine = Engine.GlobalEngine;
			engine.BinPath = @"C:\Program Files (x86)\MSBuild";
			project = new Project();
			buildEngine = mocks.DynamicMock<MockBuildEngine>(project);

			logger = new NullLogger();
			parserService = mocks.DynamicMock<ISiteTreeGeneratorService>();
			naming = mocks.DynamicMock<INamingService>();
			sourceStorage = mocks.DynamicMock<IParsedSourceStorageService>();
			source = mocks.DynamicMock<ISourceGenerator>();
			typeResolver = mocks.DynamicMock<ITypeResolver>();
			treeService = mocks.DynamicMock<ITreeCreationService>();
			viewSourceMapper = mocks.DynamicMock<IViewSourceMapper>();
			generator = mocks.DynamicMock<IGenerator>();

			task = new GenerateMonoRailSiteTreeTask(logger, parserService, naming, source, sourceStorage, typeResolver,
			                                         treeService, viewSourceMapper, generator);

			item = mocks.DynamicMock<ITaskItem>();
			parsedSource = mocks.DynamicMock<IParser>();
		}
 public object ReadYaml(IParser parser, Type type)
 {
     var scalar = (YamlDotNet.Core.Events.Scalar)parser.Current;
     var bytes = Convert.FromBase64String(scalar.Value);
     parser.MoveNext();
     return bytes;
 }
Ejemplo n.º 3
0
 public void Download(Uri uri, object metaData, IParser parser)
 {
     uriParserPairs.Add(metaData, parser);
     var request = (HttpWebRequest)WebRequest.Create(uri);
     var state = new RequestState { Request = request, Metadata = metaData };
     request.BeginGetResponse(GetData, state);
 }
Ejemplo n.º 4
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ReportBuilder"/> class.
        /// </summary>
        /// <param name="parser">The IParser to use.</param>
        /// <param name="rendererFactory">The renderer factory.</param>
        /// <param name="targetDirectory">The directory where the generated report should be saved.</param>
        /// <param name="assemblyFilter">The assembly filter.</param>
        public ReportBuilder(IParser parser, IRendererFactory rendererFactory, string targetDirectory, IAssemblyFilter assemblyFilter)
        {
            if (parser == null)
            {
                throw new ArgumentNullException("parser");
            }

            if (rendererFactory == null)
            {
                throw new ArgumentNullException("rendererFactory");
            }

            if (targetDirectory == null)
            {
                throw new ArgumentNullException("targetDirectory");
            }

            if (assemblyFilter == null)
            {
                throw new ArgumentNullException("assemblyFilter");
            }

            this.parser = parser;
            this.rendererFactory = rendererFactory;
            this.targetDirectory = targetDirectory;
            this.assemblyFilter = assemblyFilter;
        }
Ejemplo n.º 5
0
 public RazorMailSender(MailAddress sender, Uri baseUri, SmtpClient client, IParser parser)
 {
     Sender = sender;
     BaseUri = baseUri;
     Client = client ?? new SmtpClient("127.0.0.1");
     Parser = parser ?? new HtmlAgilityPackParser(baseUri);
 }
Ejemplo n.º 6
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ReportGenerator" /> class.
        /// </summary>
        /// <param name="parser">The IParser to use.</param>
        /// <param name="assemblyFilter">The assembly filter.</param>
        /// <param name="classFilter">The class filter.</param>
        /// <param name="renderers">The renderers.</param>
        internal ReportGenerator(IParser parser, IFilter assemblyFilter, IFilter classFilter, IEnumerable<IReportBuilder> renderers)
        {
            if (parser == null)
            {
                throw new ArgumentNullException("parser");
            }

            if (assemblyFilter == null)
            {
                throw new ArgumentNullException("assemblyFilter");
            }

            if (classFilter == null)
            {
                throw new ArgumentNullException("classFilter");
            }

            if (renderers == null)
            {
                throw new ArgumentNullException("renderers");
            }

            this.parser = parser;
            this.assemblyFilter = assemblyFilter;
            this.classFilter = classFilter;
            this.renderers = renderers;
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ParserAnalyzer" /> with the specified weight.
        /// </summary>
        /// <param name="parser">The parser.</param>
        /// <param name="weight">The analyzer weight.</param>
        /// <exception cref="System.ArgumentNullException">parser</exception>
        public ParserAnalyzer(IParser parser, float weight)
            : base(weight) {
            if (parser == null)
                throw new ArgumentNullException("parser");

            Parser = parser;
        }
        public static void MyClassInitialize(TestContext testContext)
        {
            FileManager.CopyTestClasses();

            var report = XDocument.Load(filePath);
            parser = new OpenCoverParser(report);
        }
		public void Add(string path, IParser parser)
		{
			if (cache.ContainsKey(path))
				throw new ArgumentException(String.Format("Source for {0} already cached!", path));
		
			cache[path] = parser;
		}
Ejemplo n.º 10
0
 /// <summary>
 /// Creates the Importer object
 /// </summary>
 /// <param name="Parser">Parser to be used for reading the stream</param>
 /// <param name="ConnectionString">Connection string of the Target DB</param>
 /// <param name="TargetTableName"> Table Name in the target DB to which the data to be pushed</param>
 /// <param name="BatchCount">Batch Size for Sql Pushing</param>
 public Importer(IParser Parser, string ConnectionString, string TargetTableName, int BatchCount)
 {
     _parser = Parser;
     _connectionString = ConnectionString;
     _targetTableName = TargetTableName;
     _batchCount = BatchCount;
 }
Ejemplo n.º 11
0
 private static void MainLoop(ILexer lexer, IParser parser)
 {
     // top ::= definition | external | expression | ';'
     while (true)
     {
         Console.Write("ready> ");
         switch (lexer.CurrentToken)
         {
         case (int)Token.EOF:
             return;
         case ';':
             lexer.GetNextToken();
             break;
         case (int)Token.DEF:
             parser.HandleDefinition();
             break;
         case (int)Token.EXTERN:
             parser.HandleExtern();
             break;
         default:
             parser.HandleTopLevelExpression();
             break;
         }
     }
 }
Ejemplo n.º 12
0
 public Calculator(ICollection<IExportFactory<IOperation, OperationMetadata>> operationFactories, IParser parser)
 {
     this.parser = parser;
     this.OperationsDictionary = operationFactories.ToDictionary(
         e => e.Metadata.Operation,
         e => e.CreateExport().Value);
 }
Ejemplo n.º 13
0
        /// <summary>
        /// Parses the specified <see cref="ISentence"/> object using a given <paramref name="parser"/>.
        /// </summary>
        /// <param name="sentence">The sentence to be parsed.</param>
        /// <param name="parser">The parser.</param>
        /// <param name="numParses">The number parses. Usually 1.</param>
        /// <returns>An array with the parsed results.</returns>
        /// <exception cref="System.ArgumentNullException">
        /// <paramref name="sentence"/>
        /// or
        /// <paramref name="parser"/>
        /// </exception>
        /// <exception cref="System.ArgumentOutOfRangeException">numParses</exception>
        /// <exception cref="System.InvalidOperationException">The sentence is not tokenized.</exception>
        public static Parse[] ParseLine(ISentence sentence, IParser parser, int numParses) {
            if (sentence == null)
                throw new ArgumentNullException("sentence");

            if (parser == null)
                throw new ArgumentNullException("parser");

            if (numParses < 0)
                throw new ArgumentOutOfRangeException("numParses");

            if (sentence.Tokens == null || sentence.Tokens.Count == 0)
                throw new InvalidOperationException("The sentence is not tokenized.");

            var sb = new StringBuilder(sentence.Length);
            for (var i = 0; i < sentence.Tokens.Count; i++) {
                sb.Append(sentence.Tokens[i].Lexeme).Append(' ');
            }
            sb.Remove(sb.Length - 1, 1);

            var start = 0;
            var p = new Parse(sb.ToString(), new Span(0, sb.Length), AbstractBottomUpParser.INC_NODE, 0, 0);

            for (var i = 0; i < sentence.Tokens.Count; i++) {
                p.Insert(
                    new Parse(
                        sb.ToString(), 
                        new Span(start, start + sentence.Tokens[i].Lexeme.Length),
                        AbstractBottomUpParser.TOK_NODE, 0, i));

                start += sentence.Tokens[i].Lexeme.Length + 1;
            }

            return numParses == 1 ? new[] { parser.Parse(p) } : parser.Parse(p, numParses);
        }
Ejemplo n.º 14
0
        /// <summary>
        /// Constructor.
        /// </summary>
        /// <param name="parser">Parser implementation</param>
        /// <param name="printResults">Action to be invoked after the processing has finished</param>
        public ConsumerUnit(IParser<string> parser, Action<IEnumerable<string>> printResults)
        {
            Parser = parser;
            PrintResults = printResults;

            Results = new List<string>();
        }
Ejemplo n.º 15
0
 public StartParsing(IFilePaths filePaths, ILogFileReaderList logfileReaderList, ILogStatisticsRepository logStatisticsRepository, IParser parser)
 {
     _filePaths = filePaths;
     _logfileReaderList = logfileReaderList;
     _logStatisticsRepository = logStatisticsRepository;
     _parser = parser;
 }
Ejemplo n.º 16
0
 private IEnumerable<ParsingEvent> EnumerationOf(IParser parser)
 {
     while (parser.MoveNext())
     {
         yield return parser.Current;
     }
 }
Ejemplo n.º 17
0
 public ExecutionContext(IParser parser)
 {
     Parser = parser;
     CaseSensitive = false;
     Store = CaseSensitive ? new Dictionary<string, ContextValue>() : new Dictionary<string, ContextValue>(StringComparer.InvariantCultureIgnoreCase);
     Dependencies = CaseSensitive ? new Dictionary<string, HashSet<string>>() : new Dictionary<string, HashSet<string>>(StringComparer.InvariantCultureIgnoreCase);
 }
Ejemplo n.º 18
0
 public FileReader(IParser parser, string path )
 {
     this.parser = parser;
     //TODO make this more generic
     icdString = File.ReadAllText(path);
     parser.ParseIcdCatalog(icdString);
 }
Ejemplo n.º 19
0
        public MainWindow()
        {
            InitializeComponent();

            pathToGit = new FileInfo(@"C:\Program Files (x86)\Git\bin\git.exe");
            try
            {
                DirectoryCatalog catalog =
                    new DirectoryCatalog(new FileInfo(Assembly.GetAssembly(typeof (MainWindow)).Location).DirectoryName);
                CompositionContainer container = new CompositionContainer(catalog);
                container.ComposeParts(this);
            }
            catch (CompositionException)
            {
                sqlParser = null;
            }

            var vm = new MainWindowViewModel(Properties.Settings.Default.Databases);
            vm.SourceChangeset = (DvcsScriptRepositoryBase.RevisionIdentifierBase)Properties.Settings.Default.LastChangeset ?? Properties.Settings.Default.LastTag;
            if (vm.SourceChangeset != null)
            {
                vm.SelectedSourceType = RevisionIdentifierConverter.GetLabelFromType(vm.SourceChangeset.GetType());
            }

            var riConverter = (RevisionIdentifierConverter)Resources["riConverter"];
            riConverter.DataContext = vm;
            DataContext = vm;
        }
Ejemplo n.º 20
0
		void DoTestEnums (IParser parser)
		{
			ICompilationUnit unit = parser.Parse (null, "a.cs", 
@"enum TestEnum {
	A,
	B,
	C
}").CompilationUnit;
			Assert.AreEqual (1, unit.Types.Count);
			IType type = unit.Types[0];
			Assert.AreEqual (ClassType.Enum, type.ClassType);
			Assert.AreEqual ("TestEnum", type.Name);
			Assert.AreEqual (3, type.FieldCount);
			foreach (IField f in type.Fields) {
				Assert.IsTrue (f.IsConst);
				Assert.IsTrue (f.IsSpecialName);
				Assert.IsTrue (f.IsPublic);
				if (f.Name == "A") {
					Assert.AreEqual (2, f.Location.Line);
				} else if (f.Name == "B") {
					Assert.AreEqual (3, f.Location.Line);
				} else if (f.Name == "C") {
					Assert.AreEqual (4, f.Location.Line);
				} else {
					Assert.Fail ("Unknown field: " + f.Name);
				}
			}
		}
Ejemplo n.º 21
0
 public ParserUi(IParser parser,ICGunitHost host)
 {
     InitializeComponent();
     m_parser = parser;
     m_Host = host;
     m_Host.evProjectStatus += new onProjectStatus(Owner_evProjectStatus);
 }
Ejemplo n.º 22
0
		public	ExpEvaluator(IParser _parser,IOperatorImp _ops)
		{
			//Use IParser to parse it 
			_OpInst = _ops;
			_exp_parser = _parser;
			// TODO: Add constructor logic here
		}
Ejemplo n.º 23
0
 /// <summary>
 /// Instantiates a build script object.
 /// </summary>
 /// <remarks>
 /// This constructor will attempt to parse the given SQL and determine whether it is valid 
 /// and whether the script creates the object specified by the given identifier.  If the 
 /// script is invalid in anyway, the <see cref="ScriptError"/> property will reflect that.
 /// </remarks>
 /// <param name="scriptObject">The identifier of the database object to build.</param>
 /// <param name="scriptContent">The build script SQL content.</param>
 /// <param name="parser">The sql script parser for reading the SQL script content.</param>
 public ScriptFile(TypedDatabaseObject scriptObject, string scriptContent, IParser parser)
 {
     ScriptObject = scriptObject;
     Content = scriptContent;
     existingDependencies = new HashSet<TypedDatabaseObject>();
     try
     {
         Sql = parser.ParseSqlScript(scriptContent);
         AssertMatchingContent();
     }
     catch (SqlParseException ex)
     {
         ScriptError = new SqlParseError(ex.Message);
         Sql = null;
     }
     catch(EmptyTextException)
     {
         ScriptError = new EmptyTextError();
         Sql = null;
     }
     catch(MultipleStatementException ex)
     {
         ScriptError = new MultipleStatementError(ex.Count, ex.Allotment);
         Sql = null;
     }
     catch(UnexpectedObjectTypeException ex)
     {
         ScriptError = new UnexpectedObjectTypeError(ex.TypeName);
         Sql = null;
     }
 }
Ejemplo n.º 24
0
		public	ExpEvaluator(IParser _parser)
		{
			//Use IParser to parse it 
			_exp_parser = _parser;

			// TODO: Add constructor logic here
		}
Ejemplo n.º 25
0
        public object DeserializeValue(IParser parser, Type expectedType, SerializerState state, IValueDeserializer nestedObjectDeserializer)
        {
            var nodeEvent = parser.Peek<NodeEvent>();

            var nodeType = GetTypeFromEvent(nodeEvent, expectedType);

            try
            {
                foreach (var deserializer in deserializers)
                {
                    object value;
                    if (deserializer.Deserialize(parser, nodeType, (r, t) => nestedObjectDeserializer.DeserializeValue(r, t, state, nestedObjectDeserializer), out value))
                    {
                        return value;
                    }
                }
            }
            catch (YamlException)
            {
                throw;
            }
            catch (Exception ex)
            {
                throw new YamlException(nodeEvent.Start, nodeEvent.End, "Exception during deserialization", ex);
            }

            throw new YamlException(
                nodeEvent.Start,
                nodeEvent.End,
                string.Format(
                    "No node deserializer was able to deserialize the node into type {0}",
                    expectedType.AssemblyQualifiedName
                )
            );
        }
 public Database Create(FileInfo pathToGit, IParser sqlParser)
 {
     var connectionStr = ConnectionString;
     Func<SqlConnection> connection = () => new SqlConnection(connectionStr);
     var repo = new GitScriptRepository(ScriptsPath, ServerName, DatabaseName, pathToGit, sqlParser);
     return new Database(ServerName, DatabaseName, connection, repo);
 }
Ejemplo n.º 27
0
 public void a_scanner_and_some_terminals()
 {
     scanner = new ScanStrings(Input) { SkipWhitespace = true };
     __this__ = new LiteralString("this");
     __is__ = new LiteralString("is");
     __wally__ = new LiteralString("wally");
     __dr_jones__ = new LiteralString("Dr. Jones!");
 }
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="AccessModifier">Access modifier</param>
 /// <param name="ClassName">Class name</param>
 /// <param name="ParameterList">Parameter list</param>
 /// <param name="Body">Body of the constructor</param>
 /// <param name="Parser">Parser to use</param>
 public Constructor(AccessModifier AccessModifier, string ClassName, IParameter[] ParameterList, string Body, IParser Parser)
     : base(Parser)
 {
     this.AccessModifier = AccessModifier;
     this.ClassName = ClassName;
     this.Parameters = ParameterList.ToList();
     this.Body = Body;
 }
Ejemplo n.º 29
0
 public LanguageCompiler(Grammar grammar)
 {
     Grammar = grammar;
       grammar.Init();
       ScannerControlData scannerData = new ScannerControlData(grammar);
       Scanner = new Scanner(scannerData);
       Parser = new Lalr.Parser(Grammar);
 }
Ejemplo n.º 30
0
 public Dict(string name, HtmlVersion versions, int model, IParser parser, ICheckAttribs checkAttribs)
 {
     _name = name;
     _versions = versions;
     _model = model;
     _parser = parser;
     _checkAttribs = checkAttribs;
 }
Ejemplo n.º 31
0
 public EMListElements(EMDocument doc, EMElementOrigin origin, EMElement parent, EMListType type)
     : base(doc, origin, parent)
 {
     parser = GetParserByType(type);
 }
Ejemplo n.º 32
0
 public static IParser <T, DateTimeParseOptions> FormatProvider <T>(this IParser <T, DateTimeParseOptions> parser, IFormatProvider value) =>
 parser.WithOptions(parser.Options.WithFormatProvider(value));
Ejemplo n.º 33
0
 public static IParser <T, DateTimeParseOptions> Format <T>(this IParser <T, DateTimeParseOptions> parser, params string[] value) =>
 parser.WithOptions(parser.Options.WithFormats(value.ToImmutableArray()));
Ejemplo n.º 34
0
 public static IParser <T, NumberParseOptions> Styles <T>(this IParser <T, NumberParseOptions> parser, NumberStyles value) =>
 parser.WithOptions(parser.Options.WithStyles(value));
Ejemplo n.º 35
0
 public DataFileParser(IParser headerParser, IParser recordParser)
 {
     _headerParser = headerParser as IParser <DataMeta>;
     _recordParser = recordParser as IRecordParser <T>;
 }
Ejemplo n.º 36
0
 public T Deserialize <T>(IParser parser)
 {
     return((T)Deserialize(parser, typeof(T)));
 }
 public void Setup()
 {
     _parser = new StringExpressionParser();
 }
Ejemplo n.º 38
0
 public static IParser <TInput, TOutput> RightApply <TMiddle, TOutput>(IParser <TInput, TOutput> item, IParser <TInput, TMiddle> middle, Func <TOutput, TMiddle, TOutput, TOutput> produce, Func <IParseState <TInput>, TOutput>?getMissingRight = null, Quantifier quantifier = Quantifier.ZeroOrMore)
 => new RightApply <TInput, TMiddle, TOutput> .Parser(item, middle, args => produce(args.Left, args.Middle, args.Right), quantifier, getMissingRight);
Ejemplo n.º 39
0
        private static ILookup <Option, string> ParseOptions(Queue <string> argsQueue, IParser parser,
                                                             Dictionary <string, Option> longNameIndex, Dictionary <string, Option> shortNameIndex,
                                                             bool ignoreInvalidOptions = false)
        {
            var diagnostics = new List <string>();

            var values       = new LinkedList <Tuple <Option, string> >();
            var optionsQueue = new Queue <ParsedOption>();

            while (argsQueue.Count + optionsQueue.Count > 0)
            {
                var parsedOption = optionsQueue.Count > 0
                    ? optionsQueue.Dequeue()
                    : parser.Parse(argsQueue);
                var matchedOption =
                    parsedOption.PrefixKind == PrefixKind.Long ? LookUp(parsedOption.Key, longNameIndex) :
                    parsedOption.PrefixKind == PrefixKind.Short ? LookUp(parsedOption.Key, shortNameIndex) :
                    parsedOption.PrefixKind == PrefixKind.Either ? LookUp(parsedOption.Key, longNameIndex, shortNameIndex) :
                    parsedOption.PrefixKind == PrefixKind.None ? LookUp(parsedOption.Key, longNameIndex, shortNameIndex) :
                    null;
                if (matchedOption == null && !ignoreInvalidOptions)
                {
                    diagnostics.Add(Inv("Configuration flag '{0}' not found", parsedOption.Key));
                }
                else if (matchedOption != null)
                {
                    Add(values, matchedOption, parsedOption.Value);
                    optionsQueue.EnqueueAll(SafeExpand(matchedOption, parsedOption, parser, diagnostics));
                }
            }

            if (diagnostics.Any())
            {
                Check(false, PrintDiagnostics(diagnostics));
            }

            return(values.ToLookup(tuple => tuple.Item1, tuple => tuple.Item2));
        }
Ejemplo n.º 40
0
 private static IEnumerable <ParsedOption> SafeExpand(Option matchedOption, ParsedOption parsedOption, IParser parser, List <string> diagnostics)
 {
     try
     {
         return(matchedOption.Expand(parsedOption.Value));
     }
     catch (Exception e)
     {
         diagnostics.Add(Inv("Could not expand option [[ {0} ]]. Error message: {1}", parser.RenderSingleOption(parsedOption), e.GetLogEventMessage()));
         return(ParsedOption.EmptyCollection);
     }
 }
Ejemplo n.º 41
0
 /// <summary>Initializer for all the fields (and nothing more).</summary>
 private Config(IParser parser, IReadOnlyCollection <Option> allConfigurationOptions, ILookup <Option, string> configuredOptions)
 {
     Parser = parser;
     AllConfigurationOptions = allConfigurationOptions;
     ConfiguredOptionValues  = configuredOptions;
 }
Ejemplo n.º 42
0
        /// <summary>
        ///     Takes a collection of supported <see cref="Option"/>s, a queue of strings, and a <see cref="Parser"/>;
        ///     parses all strings from <paramref name="args"/>, ensures that each matches a supported option from
        ///     <paramref name="confOptions"/>, produces a <see cref="Config"/> containing parsed option values,
        ///     then calls <see cref="Validate"/> to ensure that provided options' constraints (e.g.,
        ///     <see cref="Option.IsRequired"/>, <see cref="Option.IsMultiValue"/>, <see cref="Option.TryConvertValue(string)"/>)
        ///     are all met.
        /// </summary>
        /// <remarks>
        ///     <b>Mutates <paramref name="args"/></b> (by virtue of calling <see cref="IParser.Parse(Queue{string})"/>).
        /// </remarks>
        public static Config ParseCommandLineArgs(IEnumerable <Option> confOptions, Queue <string> args, IParser parser = null, bool caseInsensitive = false, bool ignoreInvalidOptions = false)
        {
            Contract.RequiresNotNull(confOptions);
            Contract.RequiresNotNull(args);
            Contract.Requires(args.All(a => !string.IsNullOrWhiteSpace(a)));

            parser = parser ?? DefaultParser;

            var stringComparer = caseInsensitive ? StringComparer.OrdinalIgnoreCase : StringComparer.Ordinal;

            // create 'indexes' for configured options for quick lookups
            Dictionary <string, Option> longNameIndex;
            Dictionary <string, Option> shortNameIndex;

            CreateIndexes(confOptions, stringComparer, out longNameIndex, out shortNameIndex);

            // parse options and populate 'matched options' dictionary
            var matchedOptions = ParseOptions(args, parser, longNameIndex, shortNameIndex, ignoreInvalidOptions);

            // create, validate, and return new configuration
            var ans = new Config(parser, new List <Option>(confOptions), matchedOptions);

            ans.Validate();
            return(ans);
        }
Ejemplo n.º 43
0
        public object ReadYaml(IParser parser, Type type)
        {
            var value = parser.Consume <Scalar>().Value;

            return(Type.GetType(value, throwOnError: true) !); // Will throw instead of returning null
        }
 public ParserSelectManyImpl2(IParser <TChar, TSource> source, IParser <TChar, TCollection> collection, Func <TSource, TCollection, TResult> resultSelector)
 {
     this.source         = source;
     this.collection     = collection;
     this.resultSelector = resultSelector;
 }
        public IEnumerable <IParseResult <IEnumerable <TResult> > > Parse(ICursor <TSource> source)
        {
            firstParser = null;

            bool first  = true;
            var  any    = new AnyParser <TSource, TResult>(parsers);
            var  except = new List <IParser <TSource, TResult> >();

            // See the AllParser.Parse method for an explanation of the optimization that is provided by this stack
            var branches = new Stack <ICursor <TSource> >();

            using (var root = source.Branch())
            {
                branches.Push(root);

                var query = ParseResult.ReturnSuccessMany <TResult>(0)
                            .SelectMany(
                    parsers.Select(
                        parser => (Func <Tuple <IParseResult <IEnumerable <TResult> >, bool>, IEnumerable <IParseResult <IEnumerable <TResult> > > >)
                            (value =>
                {
                    if (first)
                    {
                        first       = false;
                        firstParser = parser;
                    }

                    var branch = branches.Peek();

                    // Item2 is only true when value.Item1 is the last element of its sequence.
                    if (value.Item2)
                    {
                        branch.Move(value.Item1.Length);

                        return(any.Parse(except, branch).Select(result => result.YieldMany()));
                    }
                    else
                    {
                        var remainder = branch.Remainder(value.Item1.Length);

                        branches.Push(remainder);

                        return(any.Parse(except, remainder)
                               .Select(result => result.YieldMany())
                               .OnErrorOrDisposed(() =>
                        {
                            /* Finally() cannot be used here.  SelectMany generates each value as a Tuple, indicating whether it's
                             * the last value in the sequence.  To gather that info it uses a side-effect that causes it to look-ahead
                             * in the enumerator, which would cause Finally to execute and dispose of the branch before it's used
                             * by the child sequence.  SelectMany only calls Dispose when the sequence is no longer in use.
                             */
                            branches.Pop().Dispose();
                        }));
                    }
                })),
                    (firstResult, secondResult) => firstResult.Concat(secondResult));

                // Use an iterator block to ensure that the local variables in this method aren't shared between enumerators.
                foreach (var result in query)
                {
                    yield return(result);
                }
            }
        }
Ejemplo n.º 46
0
 /// <summary>
 /// a right-associative parser where the parser attempts to parse a sequence of items and middles
 /// recursively: self := &lt;item&gt; (&lt;middle&gt; &lt;self&gt;)*.
 /// </summary>
 /// <typeparam name="TMiddle"></typeparam>
 /// <typeparam name="TOutput"></typeparam>
 /// <param name="item"></param>
 /// <param name="middle"></param>
 /// <param name="produce"></param>
 /// <param name="getMissingRight"></param>
 /// <param name="quantifier"></param>
 /// <returns></returns>
 public static IParser <TInput, TOutput> RightApply <TMiddle, TOutput>(IParser <TInput, TOutput> item, IParser <TInput, TMiddle> middle, Func <RightApply <TInput, TMiddle, TOutput> .Arguments, TOutput> produce, Func <IParseState <TInput>, TOutput>?getMissingRight = null, Quantifier quantifier = Quantifier.ZeroOrMore)
 => new RightApply <TInput, TMiddle, TOutput> .Parser(item, middle, produce, quantifier, getMissingRight);
Ejemplo n.º 47
0
 public object Deserialize(IParser parser)
 {
     return(Deserialize(parser, typeof(object)));
 }
Ejemplo n.º 48
0
 /// <summary>
 /// A left-associative parser where the left item is parsed unconditionally, and the result of the
 /// left parser is applied to the right parser. This new result is then treated as the 'left' value
 /// for the next iteration of the right parser. This can be used when many rules have a common prefix
 /// and you don't want to backtrack through the prefix on every attempt.
 /// </summary>
 /// <typeparam name="TOutput"></typeparam>
 /// <param name="left"></param>
 /// <param name="getRight"></param>
 /// <param name="quantifier"></param>
 /// <returns></returns>
 public static IParser <TInput, TOutput> LeftApply <TOutput>(IParser <TInput, TOutput> left, Func <IParser <TInput, TOutput>, IParser <TInput, TOutput> > getRight, Quantifier quantifier = Quantifier.ZeroOrMore)
 => new LeftApply <TInput, TOutput> .Parser(left, getRight, quantifier);
Ejemplo n.º 49
0
 public Engine(IReader reader, IWriter writer, IParser parser)
 {
     this.reader = reader;
     this.writer = writer;
     this.parser = parser;
 }
Ejemplo n.º 50
0
 public static IParser <T> Choose <T>(this IParser <T> parser, IEqualityComparer <T> comparer, params T[] choices) =>
 from v in parser
     where choices.Contains(v, comparer)
 select v;
 internal BinaryOperatorParser(IDictionary <char, BinaryOperatorFactory> supportedOperators, IParser next)
 {
     _supportedOperators = supportedOperators;
     _next = next;
 }
Ejemplo n.º 52
0
        protected override async Task <IEnumerable <TSchema> > GetDataAsync <TSchema>(LocalStorageDataConfig config, int pageSize, IParser <TSchema> parser)
        {
            var uri = new Uri(string.Format("ms-appx://{0}", config.FilePath));

            StorageFile file = await StorageFile.GetFileFromApplicationUriAsync(uri);

            IRandomAccessStreamWithContentType randomStream = await file.OpenReadAsync();

            using (StreamReader r = new StreamReader(randomStream.AsStreamForRead()))
            {
                return(await parser.ParseAsync(await r.ReadToEndAsync()));
            }
        }
Ejemplo n.º 53
0
 public static IParser <T> Choose <T>(this IParser <T> parser, params T[] choices) =>
 parser.Choose(EqualityComparer <T> .Default, choices);
Ejemplo n.º 54
0
 /// <summary>
 /// Initializes a new instance of the <see cref="YamlScalarNode"/> class.
 /// </summary>
 internal YamlScalarNode(IParser parser, DocumentLoadingState state)
 {
     Load(parser, state);
 }
Ejemplo n.º 55
0
 void IYamlConvertible.Read(IParser parser, Type expectedType, ObjectDeserializer nestedObjectDeserializer)
 {
     Load(parser, new DocumentLoadingState());
 }
Ejemplo n.º 56
0
 public DebugTraceMessageClassifier(IParser <DebugTraceMessageData> parser) : base(parser)
 {
 }
Ejemplo n.º 57
0
 public static IParser <T, DateTimeParseOptions> Styles <T>(this IParser <T, DateTimeParseOptions> parser, DateTimeStyles value) =>
 parser.WithOptions(parser.Options.WithStyles(value));
 public static ParserSelectManyImpl2 <TChar, TSource, TCollection, TResult> SelectMany <TChar, TSource, TCollection, TResult>(this IParser <TChar, TSource> source, IParser <TChar, TCollection> collection, Func <TSource, TCollection, TResult> resultSelector)
 {
     return(new ParserSelectManyImpl2 <TChar, TSource, TCollection, TResult>(source, collection, resultSelector));
 }
Ejemplo n.º 59
0
 public static IParser <T?> Nullable <T>(this IParser <T> parser) where T : struct =>
 parser.Cast <T?>();
Ejemplo n.º 60
0
 public OrdinalModel(IParser parser, IExtractor extractor) : base(parser, extractor)
 {
 }