예제 #1
0
파일: Program.cs 프로젝트: Virtlink/noofax
		/// <summary>
		/// The entry point method.
		/// </summary>
		/// <param name="args">The command line arguments.</param>
		private static void Main(string[] args)
		{
			var pargs = ProgramArguments.Parse(args);

			Contract.Assert(pargs.ParseTablePath != null);

			var termFactory = new TrivialTermFactory();

			var productionFormat = new TermProductionFormat(termFactory);

			var parserFactory = new ParserFactory(
				new SpoofaxParseTableFormat(termFactory, productionFormat),
				new TrivialParseNodeFactory(),
				new AsFixTreeBuilder(termFactory, productionFormat));
			
			var parser = parserFactory.Create(pargs.ParseTablePath);
			
			ITerm ast;
			using (var reader = new StreamReader(FileExt.OpenInput(pargs.InputPath)))
			{
				ast = parser.Parse(reader);
			}

			// TODO: Print the ast.


			Program.trace.TraceData(TraceEventType.Information, 0, ast);
		}
예제 #2
0
 internal Language(MImage image, string moduleName, string languageName)
 {
     this.image = image;
     this.moduleName = moduleName;
     this.languageName = languageName;
     this.factory = this.image.ParserFactories[moduleName + "." + languageName];
 }
 public void factory_should_throw_exception_if_arguments_are_invalid()
 {
     var factory = new ParserFactory();
     var contacts = string.Empty;
     Assert.Throws(typeof(ArgumentNullException),
                   () => factory.Create(contacts, null));
 }
 public void factory_should_return_string_parser_if_contacts_are_passed_in()
 {
     var factory = new ParserFactory();
     var contacts = "*****@*****.**";
     var parser = factory.Create(contacts, null);
     Assert.IsInstanceOfType(typeof(StringParser), parser,
                             "Wrong parser type returned");
 }
예제 #5
0
파일: Parser.cs 프로젝트: st9200/soal-oslo
        public Parser(ParserFactory parserFactory)
        {
            this.parser = parserFactory.Create();
            this.store = new DefaultGraphStore();
            this.locations = new Dictionary<object, SourceSpan>();
            this.parser.GraphBuilder = new NodeGraphBuilder(store);

            this.parser.SyntaxMatched += new EventHandler<SyntaxMatchedEventArgs>(parser_SyntaxMatched);
        }
 public void factory_should_throw_exception_if_file_format_is_not_supported()
 {
     var factory = new ParserFactory();
     var contacts = string.Empty;
     var mockUploadedTextFile = new Mock<HttpPostedFileBase>();
     mockUploadedTextFile.Expect(f => f.FileName).Returns("textfile.xls");
     Assert.Throws(typeof(NotImplementedException),
                   () => factory.Create(contacts, mockUploadedTextFile.Object));
 }
 public void factory_should_return_text_file_parser_for_uploaded_text_files()
 {
     var factory = new ParserFactory();
     var contacts = string.Empty;
     var mockUploadedTextFile = new Mock<HttpPostedFileBase>();
     mockUploadedTextFile.Expect(f => f.FileName).Returns("textfile.txt");
     var parser = factory.Create(contacts, mockUploadedTextFile.Object);
     Assert.IsInstanceOfType(typeof(TextFileParser), parser,
                             "Wrong parser type returned");
 }
예제 #8
0
 public void Install(IWindsorContainer container, IConfigurationStore store)
 {
     container.Register(
         Component.For<ParserFactory>().UsingFactoryMethod<ParserFactory>(kernel =>
         {
             var factory = new ParserFactory();
             factory.ParserLookup = kernel.Resolve<FieldAssembler>().ParserLookup;
             return factory;
         }));
 }
예제 #9
0
        public InvokeRule(ParserFactory factory, GrammarAST ast, GrammarAST labelAST)
            : base(factory, ast)
        {
            if (ast.atnState != null)
            {
                RuleTransition ruleTrans = (RuleTransition)ast.atnState.Transition(0);
                stateNumber = ast.atnState.stateNumber;
            }

            this.name = ast.Text;
            Rule r = factory.GetGrammar().GetRule(name);
            ctxName = factory.GetTarget().GetRuleFunctionContextStructName(r);

            // TODO: move to factory
            RuleFunction rf = factory.GetCurrentRuleFunction();
            if (labelAST != null)
            {
                // for x=r, define <rule-context-type> x and list_x
                string label = labelAST.Text;
                if (labelAST.Parent.Type == ANTLRParser.PLUS_ASSIGN)
                {
                    factory.DefineImplicitLabel(ast, this);
                    string listLabel = factory.GetTarget().GetListLabel(label);
                    RuleContextListDecl l = new RuleContextListDecl(factory, listLabel, ctxName);
                    rf.AddContextDecl(ast.GetAltLabel(), l);
                }
                else
                {
                    RuleContextDecl d = new RuleContextDecl(factory, label, ctxName);
                    labels.Add(d);
                    rf.AddContextDecl(ast.GetAltLabel(), d);
                }
            }

            ActionAST arg = (ActionAST)ast.GetFirstChildWithType(ANTLRParser.ARG_ACTION);
            if (arg != null)
            {
                argExprsChunks = ActionTranslator.TranslateAction(factory, rf, arg.Token, arg);
            }

            // If action refs rule as rulename not label, we need to define implicit label
            if (factory.GetCurrentOuterMostAlt().ruleRefsInActions.ContainsKey(ast.Text))
            {
                string label = factory.GetTarget().GetImplicitRuleLabel(ast.Text);
                RuleContextDecl d = new RuleContextDecl(factory, label, ctxName);
                labels.Add(d);
                rf.AddContextDecl(ast.GetAltLabel(), d);
            }
        }
예제 #10
0
 public static void LoadFields(this List <EntityField> me, IEnumerable <EntityFieldMetaData> fieldsMetaData, ParserFactory parserFactory)
 {
     // [Field + Parsers]
     foreach (var fieldMD in fieldsMetaData)
     {
         var field = (EntityField)fieldMD;
         field.Parsers.LoadParsers(fieldMD.ParsersMetaData, parserFactory);
         me.Add(field);
     }
     ;
 }
예제 #11
0
 /// <summary>Creates an empty KnowledgeBase using in memory storage of resource descriptions.</summary>
 /// <param name="parserFactory">A ParserFactory that the KnowledgeBase should use to create new RDF parsers</param>
 public KnowledgeBase(ParserFactory parserFactory) : this(new MemoryTripleStoreFactory(), parserFactory)
 {
 }
        internal static Task <int> BindValues(CommandContext commandContext, ExecutionDelegate next)
        {
            var console       = commandContext.Console;
            var parserFactory = new ParserFactory(commandContext.AppConfig.AppSettings);

            bool SetFromStringInput(IArgument argument, IEnumerable <string> values, out int returnCode)
            {
                try
                {
                    var parser = parserFactory.CreateInstance(argument);
                    var value  = parser.Parse(argument, values);
                    argument.Value = value;
                    returnCode     = 0;
                    return(true);
                }
                catch (ValueParsingException ex)
                {
                    console.Error.WriteLine($"Failure parsing value for {argument}.  values={values?.ToCsv()}");
                    console.Error.WriteLine(ex.Message);
                    console.Error.WriteLine();
                    returnCode = 2;
                    return(false);
                }
            }

            var arguments = commandContext.InvocationPipeline.All
                            .SelectMany(ic => ic.Command.Options.Cast <IArgument>().Union(ic.Command.Operands))
                            .Where(a => a.GetArgumentDef() != null);

            foreach (var argument in arguments)
            {
                if (argument.InputValues.Any())
                {
                    if (!SetFromStringInput(argument, argument.InputValues.SelectMany(iv => iv.Values), out int returnCode))
                    {
                        return(Task.FromResult(returnCode));
                    }
                }
                else if (argument.DefaultValue != null)
                {
                    var defaultValue = argument.DefaultValue;
                    // middleware could set the default to any type.
                    // string values could be assigned from attributes or config values
                    // so they are parsed as if submitted from the shell.
                    switch (defaultValue)
                    {
                    case string stringValue:
                        if (!SetFromStringInput(argument, stringValue.ToEnumerable(), out int returnCode))
                        {
                            return(Task.FromResult(returnCode));
                        }

                        break;

                    case IEnumerable <string> multiString:
                        if (!SetFromStringInput(argument, multiString, out returnCode))
                        {
                            return(Task.FromResult(returnCode));
                        }

                        break;

                    default:
                        try
                        {
                            var argumentType = argument.TypeInfo.Type;
                            if (argumentType.IsInstanceOfType(defaultValue))
                            {
                                argument.Value = defaultValue;
                            }
                            else
                            {
                                // cover cases like converting int to long.
                                var convertedValue = Convert.ChangeType(defaultValue, argumentType);
                                argument.Value = convertedValue;
                            }
                        }
                        catch (Exception ex)
                        {
                            console.Error.WriteLine(
                                $"Failure assigning value to {argument}. Value={defaultValue}");
                            console.Error.WriteLine(ex.Message);
                            console.Error.WriteLine();
                            return(Task.FromResult(2));
                        }

                        break;
                    }
                }
            }

            return(next(commandContext));
        }
예제 #13
0
        public override string Solve()
        {
            var data = ParserFactory.CreateMultiLineStringParser().GetData().ToList();

            return("");
        }
예제 #14
0
        public void Markdown_Generated_WhenValidSlideProvided()
        {
            #region vars

            var xml = @"<?xml version='1.0' encoding='utf-8' ?>
  <Slide Title='Dependency Injection with Windsor Castle' Margin='-200,0,0,0'>
      <RichTextBlock FontSize='20' FontWeight='DemiBold'>     
           <Paragraph>     
             <Bold>Windsor Castle Container</Bold>        
           </Paragraph>
           <Paragraph>
            <Run>Dependency Injection</Run>
           </Paragraph>
           </RichTextBlock>
        
           <Component Id='94928827-5412-4BC8-A279-EB88E21AC64F' Name='Windsor Castle' IsBrowsable='true' Action='View' TargetFile='IoC\ServiceInstaller.cs' TargetProject='Code.Service' Language='csharp'>
                   
             <Code>
                   <![CDATA[ using Castle.Windsor;
            using Castle.Windsor.Installer;
            using Castle.MicroKernel.Registration;
            using Castle.MicroKernel.SubSystems.Configuration;

            var container = new WindsorContainer();
            container.Install(FromAssembly.This());
            //usage:
            var codeServices = container.Resolve<ICodeServices>();

  public class ServiceInstaller : IWindsorInstaller
        {
            public void Install(IWindsorContainer container, IConfigurationStore store)
            {
                container.Register(
                    Component.For<IGenericServices<domain.Presentation>>()
                        .ImplementedBy<GenericServices<domain.Presentation>>()
                        .DependsOn(Dependency.OnAppSettingsValue('path'),
                          Dependency.OnAppSettingsValue('pattern'))
                        .LifestyleSingleton(),

                    Classes.FromThisAssembly()
                        .BasedOn<ApiController>()
                        .LifestyleScoped()
                    );
            }
        }]]>
      </Code>
    </Component>
  </Slide>".Trim().Replace("'", "\"");

            var expectedMarkdown = @"
    #Dependency Injection with Windsor Castle#
    
      *Windsor Castle Container*
  Dependency Injection
    ```csharp
 using Castle.Windsor;
            using Castle.Windsor.Installer;
            using Castle.MicroKernel.Registration;
            using Castle.MicroKernel.SubSystems.Configuration;

            var container = new WindsorContainer();
            container.Install(FromAssembly.This());
            //usage:
            var codeServices = container.Resolve<ICodeServices>();

  public class ServiceInstaller : IWindsorInstaller
        {
            public void Install(IWindsorContainer container, IConfigurationStore store)
            {
                container.Register(
                    Component.For<IGenericServices<domain.Presentation>>()
                        .ImplementedBy<GenericServices<domain.Presentation>>()
                        .DependsOn(Dependency.OnAppSettingsValue('path'),
                          Dependency.OnAppSettingsValue('pattern'))
                        .LifestyleSingleton(),

                    Classes.FromThisAssembly()
                        .BasedOn<ApiController>()
                        .LifestyleScoped()
                    );
            }
        }
      
    ```
  ".Replace("'", "\"");

            #endregion

            var parser = ParserFactory.CreateSlideParser(new MockApiServiceString());
            Assert.IsNotNull(parser);

            var markdown = parser.Parse(XmlHelper2 <Slide> .LoadFromString(xml)).GetAwaiter().GetResult();

            TextHelper.SaveFileContent("expected-markdown.txt", expectedMarkdown);
            TextHelper.SaveFileContent("actual-markdown.txt", markdown);
            Assert.AreEqual(expectedMarkdown.Trim(), markdown.Trim());
        }
 /// <summary>
 /// Create a deserializer instance for specified type and payload schema, using a custom object factory
 /// </summary>
 /// <param name="type">Type representing a Bond schema</param>
 /// <param name="schema">Schema of the payload</param>
 /// <param name="factory">Factory providing expressions to create objects during deserialization</param>
 /// <param name="inlineNested">Inline nested types if possible (optimizes for reduction of execution time
 /// at the expense of initialization time and memory)</param>
 public Deserializer(Type type, RuntimeSchema schema, Factory factory, bool inlineNested)
     : this(type, ParserFactory <R> .Create(schema), null, factory, inlineNested)
 {
 }
 /// <summary>
 /// Create a deserializer instance for specified type, using a custom object factory
 /// </summary>
 /// <param name="type">Type representing a Bond schema</param>
 /// <param name="factory">Factory providing expressions to create objects during deserialization</param>
 public Deserializer(Type type, Factory factory)
     : this(type, ParserFactory <R> .Create(type), null, factory)
 {
 }
예제 #17
0
 public AdditionalExpressionParser(IEnumerable <IToken> tokens, ParserFactory parserFactory) : base(tokens, parserFactory)
 {
 }
예제 #18
0
 public ReturnStatementParser(IEnumerable <IToken> tokens, ParserFactory parserFactory)
     : base(tokens, parserFactory)
 {
 }
        static CodeCompileUnit ParseInternal(TextReader codeStream)
        {
            IParser parser = ParserFactory.CreateParser(
                SupportedLanguage.CSharp,
                codeStream);

            parser.ParseMethodBodies = true;
            parser.Parse();

            if (parser.Errors.Count > 0)
            {
                throw new ArgumentException(parser.Errors.ErrorOutput);
            }

            var cdv = new CodeDomVisitor(); // new CodeDomVisitor (parser.Lexer.SpecialTracker.CurrentSpecials);

            parser.CompilationUnit.AcceptVisitor(cdv, null);

            parser.Dispose();

            CodeCompileUnit ccu = cdv.codeCompileUnit;

            //C# parser seems to insist on putting imports in the "Global" namespace; fix it up
            for (int i = 0; i < ccu.Namespaces.Count; i++)
            {
                CodeNamespace global = ccu.Namespaces [i];
                if ((global.Name == "Global") && (global.Types.Count == 0))
                {
                    global.Name = "";
                    ccu.Namespaces.RemoveAt(i);
                    ccu.Namespaces.Insert(0, global);

                    //clear out repeat imports...
                    for (int j = 1; j < ccu.Namespaces.Count; j++)
                    {
                        CodeNamespace cn = ccu.Namespaces [j];

                        //why can't we remove imports? will have to collect ones to keep
                        //then clear and refill
                        CodeNamespaceImportCollection imps = new CodeNamespaceImportCollection();

                        for (int m = 0; m < cn.Imports.Count; m++)
                        {
                            bool found = false;

                            for (int n = 0; n < global.Imports.Count; n++)
                            {
                                if (global.Imports [n] == cn.Imports [m])
                                {
                                    found = true;
                                }
                            }

                            if (!found)
                            {
                                imps.Add(cn.Imports [m]);
                            }
                        }

                        cn.Imports.Clear();

                        foreach (CodeNamespaceImport imp in imps)
                        {
                            cn.Imports.Add(imp);
                        }
                    }

                    break;
                }
            }
            return(ccu);
        }
예제 #20
0
        public void CreateParser_NoReports_CorrectParserIsReturned()
        {
            string parserName = ParserFactory.CreateParser(new string[] { string.Empty }, new string[] { }).ToString();

            Assert.AreEqual(string.Empty, parserName, "Wrong parser");
        }
예제 #21
0
 public SubroutineCallParser(IEnumerable <IToken> tokens, ParserFactory parserFactory)
     : base(tokens, parserFactory)
 {
 }
예제 #22
0
 public static void LoadFields(this IEnumerable <EntityField> me, IEnumerable <EntityFieldMetaData> fieldsMetaData, ParserFactory parserFactory)
 {
     me.ToList().LoadFields(fieldsMetaData, parserFactory);
 }
 /// <summary>
 /// Create a deserializer instance for specified type and payload schema
 /// </summary>
 /// <param name="type">Type representing a Bond schema</param>
 /// <param name="schema">Schema of the payload</param>
 public Deserializer(Type type, RuntimeSchema schema)
     : this(type, ParserFactory <R> .Create(schema))
 {
 }
 /// <summary>
 /// Create a deserializer instance for specified type, using a custom object factory
 /// </summary>
 /// <param name="type">Type representing a Bond schema</param>
 /// <param name="factory">Factory providing expressions to create objects during deserialization</param>
 /// <param name="inlineNested">Inline nested types if possible (optimizes for reduction of execution time
 /// at the expense of initialization time and memory)</param>
 public Deserializer(Type type, Factory factory, bool inlineNested)
     : this(type, ParserFactory <R> .Create(type), null, factory, inlineNested)
 {
 }
 public ParameterListAdditionalParameterParser(IEnumerable <IToken> tokens, ParserFactory parserFactory)
     : base(tokens, parserFactory)
 {
 }
 /// <summary>
 /// Create a deserializer instance for specified type
 /// </summary>
 /// <param name="type">Type representing a Bond schema</param>
 public Deserializer(Type type)
     : this(type, ParserFactory <R> .Create(type))
 {
 }
예제 #27
0
 public MovieSearchService(ParserFactory parserFactory)
 {
     m_parserFactory = parserFactory;
 }
 /// <summary>
 /// Create a deserializer instance for specified type and payload schema, using a custom object factory
 /// </summary>
 /// <param name="type">Type representing a Bond schema</param>
 /// <param name="schema">Schema of the payload</param>
 /// <param name="factory">Factory providing expressions to create objects during deserialization</param>
 public Deserializer(Type type, RuntimeSchema schema, Factory factory)
     : this(type, ParserFactory <R> .Create(schema), null, factory)
 {
 }
        private static void TestGeneratedXml(string classFileName, string xmlFileName, string contentTypeName, ParserFactory factory)
        {
            ContentType contentType;
            string      expectedOutput;

            using (var goldReader = File.OpenText(@"..\..\TestFiles\" + xmlFileName + ".xml"))
            {
                expectedOutput = goldReader.ReadToEnd();
            }

            var contentTypeConfig = CodeGeneratorConfiguration.Create().Get(contentTypeName);

            contentTypeConfig.BaseClass = "Umbraco.Core.Models.TypedModelBase";

            using (var inputReader = File.OpenText(@"..\..\TestFiles\" + classFileName + ".cs"))
            {
                var codeParser = new CodeParser(contentTypeConfig, TestDataTypeProvider.All, factory);
                contentType = codeParser.Parse(inputReader).Single();
            }

            var serializer = new ContentTypeSerializer();
            var xml        = serializer.Serialize(contentType);

            Console.WriteLine(xml);

            Assert.AreEqual(expectedOutput, xml);
        }
예제 #30
0
 ILexer GenerateLexer(StringReader sr)
 {
     return(ParserFactory.CreateLexer(SupportedLanguage.VBNet, sr));
 }
        public void DoCloneDetection(string codefile, MethodsOnASingleClassCloneFinder cloneFinder)
        {
            string codeText = File.ReadAllText(codefile);

            TestLog.EmbedPlainText("The Code", codeText);

//            System.Diagnostics.Debugger.Break();

            IParser parser = ParserFactory.CreateParser(SupportedLanguage.CSharp, new StringReader(codeText));

            parser.Parse();

            if (parser.Errors.Count > 0)
            {
                throw new ApplicationException(string.Format("Expected no errors in the input code. Code was: {0} ErrorOutput: {1}", codeText,
                                                             parser.Errors.ErrorOutput));
            }

            var comments = parser.Lexer.SpecialTracker.RetrieveSpecials().OfType <Comment>();

            if (comments.Any(x => x.CommentText.TrimStart().StartsWith("Ignore")))
            {
                throw new ApplicationException("Ignored.");
            }

            var begin_comment = comments.FirstOrDefault(x => x.CommentText.Contains("BEGIN"));
            var end_comment   = comments.FirstOrDefault(x => x.CommentText.Contains("END"));

            if (begin_comment == null)
            {
                throw new ApplicationException("There was no comment containing the BEGIN keyword.");
            }
            if (end_comment == null)
            {
                throw new ApplicationException("There was no comment containing the END keyword.");
            }

            CloneDesc largest = null;

            cloneFinder.OnExtractedCandidate += (finder, args) =>
            {
                if (largest == null)
                {
                    largest = args.Candidate;
                }
                else if (args.Candidate.ReplacementInvocationInfo.ReplacementSectionStartLine >= begin_comment.StartPosition.Line &&
                         args.Candidate.ReplacementInvocationInfo.ReplacementSectionEndLine <= end_comment.EndPosition.Line &&
                         args.Candidate.PermutatedMethod.CountNodes() > largest.PermutatedMethod.CountNodes())
                {
                    largest = args.Candidate;
                }
            };


            var replacements = cloneFinder.GetCloneReplacements(parser.CompilationUnit);

            int clone_count = replacements.Clones.Count;

            TestLog.EmbedPlainText(clone_count + " clones found.");
            for (int i = 0; i < replacements.Clones.Count; i++)
            {
                TestLog.EmbedPlainText("   ***** Clone #" + i + " *****", replacements.Clones[i].ToString());
            }

            TestLog.EmbedPlainText("The largest permutation found within the markers was:", largest.PermutatedMethod.Print());

            var quickFixInfos = replacements.Clones.Where(Predicate(begin_comment, end_comment));

            Assert.IsTrue(quickFixInfos.Count() > 0, "None of the clones found (there were " + clone_count + ") fell inbetween the BEGIN/END markers.");

            var expected_call_snippet = begin_comment.CommentText.Substring(begin_comment.CommentText.IndexOf("BEGIN") + 5).Trim();

            if (!string.IsNullOrEmpty(expected_call_snippet))
            {
                var expected_call = ParseUtilCSharp.ParseStatement <Statement>(expected_call_snippet);
                var actual_cal    = ParseUtilCSharp.ParseStatement <Statement>(quickFixInfos.First().TextForACallToJanga);
                Assert.IsTrue(expected_call.MatchesPrint(actual_cal), "The expected call did not match the actual call.  \n\tExpected Call: " + expected_call.Print() + "\n\t" + "Actual Call: " + actual_cal.Print());
            }
        }
예제 #32
0
 public StandardAdapter(IControlFactory <T> controlFactory, IParameterBuilderFactory builderFactory, ParserFactory parserFactory)
     : base(controlFactory, builderFactory)
 {
     Parser = parserFactory;
 }
예제 #33
0
 public void TestNoParserException()
 {
     //TODO: needs to be moved into a ParserFactory specific unit test
     // Exercise
     CreateViewStatement sut = ParserFactory.Execute <CreateViewStatement>("merge from table").First();;
 }
예제 #34
0
        public override string Solve()
        {
            var regulationLookup = BagRegulation.GetRegulationsLookup(ParserFactory.CreateMultiLineStringParser().GetData());

            return(regulationLookup["shiny gold"].ContainedBagCount(regulationLookup).ToString());
        }
예제 #35
0
 public Callable_1(ICharStream input, ParserFactory factory, BlockingCollection<int> threadNumbers)
        static int FindBeginStatement(IDocument document, VBStatement statement, Location endLocation, out int length)
        {
            ILexer lexer = ParserFactory.CreateLexer(SupportedLanguage.VBNet, document.CreateReader());

            Token currentToken = null;
            Token prevToken    = null;

            int           lookFor = statement.StatementToken;
            Stack <Token> tokens  = new Stack <Token>();

            if (statement.EndStatement == "Next")
            {
                lookFor = Tokens.For;
            }

            Token result = null;

//			Token firstModifier = null;

            while ((currentToken = lexer.NextToken()).Kind != Tokens.EOF)
            {
                if (prevToken == null)
                {
                    prevToken = currentToken;
                }

//				if (IsModifier(currentToken)) {
//					if (firstModifier == null)
//						firstModifier = currentToken;
//				} else
//					firstModifier = null;


                if (VBNetFormattingStrategy.IsBlockStart(lexer, currentToken, prevToken))
                {
                    tokens.Push(currentToken);
                }
                if (VBNetFormattingStrategy.IsBlockEnd(currentToken, prevToken))
                {
                    while (tokens.Count > 0 && !VBNetFormattingStrategy.IsMatchingEnd(tokens.Peek(), currentToken))
                    {
                        tokens.Pop();
                    }
                    if (tokens.Count > 0)
                    {
                        Token t = tokens.Pop();
                        if (currentToken.Location.Line == endLocation.Line)
                        {
                            result = t;
                            break;
                        }
                    }
                }

                prevToken = currentToken;
            }

            if (result != null)
            {
                int endOffset = document.PositionToOffset(result.EndLocation.Line, result.EndLocation.Column);
                int offset    = document.PositionToOffset(result.Location.Line, result.Location.Column);
                length = endOffset - offset;
                return(offset);
            }

            length = 0;

            return(-1);
        }
예제 #37
0
 public WpfStandardAdapter(IControlFactory<UIElement> controlFactory, IParameterBuilderFactory builderFactory, ParserFactory parserFactory)
     : base(controlFactory, builderFactory)
 {
     Parser = parserFactory;
 }
예제 #38
0
 public void Select_Top_Missing_Top_Param_StarField()
 {
     // Exercise
     CreateViewStatement sut = ParserFactory.Execute <CreateViewStatement>("create view v1 as select top * from table").First();
 }
예제 #39
0
        protected void parseSources(ParserFactory factory, IEnumerable<ICharStream> sources)
        {
            Stopwatch startTime = Stopwatch.StartNew();
            Thread.VolatileWrite(ref tokenCount, 0);
            int sourceCount = 0;
            int inputSize = 0;

#if NET_4_0
            BlockingCollection<int> threadIdentifiers = new BlockingCollection<int>();
            for (int i = 0; i < NUMBER_OF_THREADS; i++)
                threadIdentifiers.Add(i);

            ICollection<Task<int>> results = new List<Task<int>>();
            QueuedTaskScheduler executorServiceHost = new QueuedTaskScheduler(NUMBER_OF_THREADS);
            TaskScheduler executorService = executorServiceHost.ActivateNewQueue();
#else
            ICollection<Func<int>> results = new List<Func<int>>();
#endif
            foreach (ICharStream input in sources)
            {
                sourceCount++;
                input.Seek(0);
                inputSize += input.Size;
#if NET_4_0
                Task<int> futureChecksum = Task.Factory.StartNew<int>(new Callable_1(input, factory, threadIdentifiers).call, CancellationToken.None, TaskCreationOptions.None, executorService);
#else
                Func<int> futureChecksum = new Callable_1(input, factory).call;
#endif
                results.Add(futureChecksum);
            }

            Checksum checksum = new CRC32();
            foreach (var future in results)
            {
#if NET_4_0
                int value = future.Result;
#else
                int value = future();
#endif
                if (COMPUTE_CHECKSUM)
                {
                    updateChecksum(checksum, value);
                }
            }

#if NET_4_0
            executorServiceHost.Dispose();
#endif

            Console.Out.WriteLine("Total parse time for {0} files ({1} KB, {2} tokens, checksum 0x{3:X8}): {4}ms",
                              sourceCount,
                              inputSize / 1024,
                              Thread.VolatileRead(ref tokenCount),
                              COMPUTE_CHECKSUM ? checksum.Value : 0,
                              startTime.ElapsedMilliseconds);

            if (sharedLexers.Length > 0)
            {
                Lexer lexer = sharedLexers[0];
                LexerATNSimulator lexerInterpreter = lexer.Interpreter;
                DFA[] modeToDFA = lexerInterpreter.atn.modeToDFA;
                if (SHOW_DFA_STATE_STATS)
                {
                    int states = 0;
                    int configs = 0;
                    HashSet<ATNConfig> uniqueConfigs = new HashSet<ATNConfig>();

                    for (int i = 0; i < modeToDFA.Length; i++)
                    {
                        DFA dfa = modeToDFA[i];
                        if (dfa == null || dfa.states == null)
                        {
                            continue;
                        }

                        states += dfa.states.Count;
                        foreach (DFAState state in dfa.states.Values)
                        {
                            configs += state.configs.Count;
                            uniqueConfigs.UnionWith(state.configs);
                        }
                    }

                    Console.Out.WriteLine("There are {0} lexer DFAState instances, {1} configs ({2} unique), {3} prediction contexts.", states, configs, uniqueConfigs.Count, lexerInterpreter.atn.GetContextCacheSize());
                }
            }

            if (RUN_PARSER && sharedParsers.Length > 0)
            {
                Parser parser = sharedParsers[0];
                // make sure the individual DFAState objects actually have unique ATNConfig arrays
                ParserATNSimulator interpreter = parser.Interpreter;
                DFA[] decisionToDFA = interpreter.atn.decisionToDFA;

                if (SHOW_DFA_STATE_STATS)
                {
                    int states = 0;
                    int configs = 0;
                    HashSet<ATNConfig> uniqueConfigs = new HashSet<ATNConfig>();

                    for (int i = 0; i < decisionToDFA.Length; i++)
                    {
                        DFA dfa = decisionToDFA[i];
                        if (dfa == null || dfa.states == null)
                        {
                            continue;
                        }

                        states += dfa.states.Count;
                        foreach (DFAState state in dfa.states.Values)
                        {
                            configs += state.configs.Count;
                            uniqueConfigs.UnionWith(state.configs);
                        }
                    }

                    Console.Out.WriteLine("There are {0} parser DFAState instances, {1} configs ({2} unique), {3} prediction contexts.", states, configs, uniqueConfigs.Count, interpreter.atn.GetContextCacheSize());
                }

                int localDfaCount = 0;
                int globalDfaCount = 0;
                int localConfigCount = 0;
                int globalConfigCount = 0;
                int[] contextsInDFAState = new int[0];

                for (int i = 0; i < decisionToDFA.Length; i++)
                {
                    DFA dfa = decisionToDFA[i];
                    if (dfa == null || dfa.states == null)
                    {
                        continue;
                    }

                    if (SHOW_CONFIG_STATS)
                    {
                        foreach (DFAState state in dfa.states.Keys)
                        {
                            if (state.configs.Count >= contextsInDFAState.Length)
                            {
                                Array.Resize(ref contextsInDFAState, state.configs.Count + 1);
                            }

                            if (state.isAcceptState)
                            {
                                bool hasGlobal = false;
                                foreach (ATNConfig config in state.configs)
                                {
                                    if (config.ReachesIntoOuterContext)
                                    {
                                        globalConfigCount++;
                                        hasGlobal = true;
                                    }
                                    else
                                    {
                                        localConfigCount++;
                                    }
                                }

                                if (hasGlobal)
                                {
                                    globalDfaCount++;
                                }
                                else
                                {
                                    localDfaCount++;
                                }
                            }

                            contextsInDFAState[state.configs.Count]++;
                        }
                    }

                    if (EXPORT_LARGEST_CONFIG_CONTEXTS)
                    {
                        foreach (DFAState state in dfa.states.Keys)
                        {
                            foreach (ATNConfig config in state.configs)
                            {
                                string configOutput = config.ToDotString();
                                if (configOutput.Length <= configOutputSize)
                                {
                                    continue;
                                }

                                configOutputSize = configOutput.Length;
                                writeFile(tmpdir, "d" + dfa.decision + ".s" + state.stateNumber + ".a" + config.Alt + ".config.dot", configOutput);
                            }
                        }
                    }
                }

                if (SHOW_CONFIG_STATS && currentPass == 0)
                {
                    Console.Out.WriteLine("  DFA accept states: {0} total, {1} with only local context, {2} with a global context", localDfaCount + globalDfaCount, localDfaCount, globalDfaCount);
                    Console.Out.WriteLine("  Config stats: {0} total, {1} local, {2} global", localConfigCount + globalConfigCount, localConfigCount, globalConfigCount);
                    if (SHOW_DFA_STATE_STATS)
                    {
                        for (int i = 0; i < contextsInDFAState.Length; i++)
                        {
                            if (contextsInDFAState[i] != 0)
                            {
                                Console.Out.WriteLine("  {0} configs = {1}", i, contextsInDFAState[i]);
                            }
                        }
                    }
                }
            }
        }
예제 #40
0
 private static IParser CreateSharpParser(string fileName)
 {
     return(ParserFactory.Create(OpenSharpModel(fileName)));
 }
예제 #41
0
            public Callable_1(ICharStream input, ParserFactory factory)
#endif
            {
                this.input = input;
                this.factory = factory;
#if NET_4_0
                this.threadNumbers = threadNumbers;
#endif
            }
예제 #42
0
        static void Main(string[] args)
        {
            var solutionFiles =
                Directory.EnumerateFiles(".", "*.sln", SearchOption.TopDirectoryOnly).ToArray();

            if (1 != solutionFiles.Length)
            {
                Error("Needs to be run from a directory with exactly one *.sln file in it.");
            }
            var solutionPath = Path.GetFullPath(solutionFiles.First());

            switch (parseCommandLine())
            {
            case (_, HelpResult help):
                Console.WriteLine(help.Text);
                Environment.Exit(help.IsResultOfInvalidInput ? -1 : 0);
                break;

            case (var helpOverview, Configuration configuration):
                if (configuration.OldProjectName.Any(CommonExtensions.IsDirectorySeparator))
                {
                    Error(
                        $"Do not specify paths for input/'old' project names, please.{Environment.NewLine}{Environment.NewLine}{helpOverview}");
                }

                configuration.OldProjectName = removeProjectFileExtension(configuration.OldProjectName);
                configuration.NewProjectName = removeProjectFileExtension(configuration.NewProjectName);

                new Application(configuration, solutionPath).Run();
                break;

            default:
                Error(
                    "Something went seriously wrong. Please create an issue at https://github.com/ModernRonin/ProjectRenamer with as much detail as possible.");
                break;
            }

            (string, object) parseCommandLine()
            {
                var parser = ParserFactory.Create("renameproject",
                                                  "Rename C# projects comfortably, including renaming directories, updating references, keeping your git history intact, creating a git commit and updating paket, if needed.");
                var cfg = parser.DefaultVerb <Configuration>();

                cfg.Parameter(c => c.DontCreateCommit)
                .WithLongName("no-commit")
                .WithShortName("nc")
                .WithHelp("don't create a commit after renaming has finished");
                cfg.Parameter(c => c.DoRunBuild)
                .WithLongName("build")
                .WithShortName("b")
                .WithHelp(
                    "run a build after renaming (but before committing) to make sure everything worked fine.");
                cfg.Parameter(c => c.DontRunPaketInstall)
                .WithLongName("no-paket")
                .WithShortName("np")
                .WithHelp("don't run paket install (if your solution uses paket as a local tool)");
                cfg.Parameter(c => c.DontReviewSettings)
                .WithLongName("no-review")
                .WithShortName("nr")
                .WithHelp("don't review all settings before starting work");
                cfg.Parameter(c => c.OldProjectName)
                .WithLongName("old-name")
                .WithShortName("o")
                .ExpectAt(0)
                .WithHelp(
                    "the name of the existing project - don't provide path or extension, just the name as you see it in VS.");
                cfg.Parameter(c => c.NewProjectName)
                .WithLongName("new-name")
                .WithShortName("n")
                .ExpectAt(1)
                .WithHelp("the new desired project name, again without path or extension");
                cfg.Parameter(c => c.ExcludedDirectory)
                .MakeOptional()
                .ExpectAt(2)
                .WithLongName("exclude")
                .WithShortName("e")
                .WithHelp(
                    "exclude this directory from project reference updates; must be a relative path to the current directory");
                return(parser.HelpOverview, parser.Parse(args));
            }

            string removeProjectFileExtension(string projectName) =>
            projectName.EndsWith(Constants.ProjectFileExtension,
                                 StringComparison.InvariantCultureIgnoreCase)
                    ? projectName[..^ Constants.ProjectFileExtension.Length]
예제 #43
0
        public void Process()
        {
            if (!Login())
            {
                return;
            }

            var transform = DataTransformFactory.GetDataTransform(-1);

            if (transform == null)
            {
                throw new DataTransformException();
            }

            var connectionError = false;

            foreach (var import in Configuration.Import)
            {
                if (connectionError)
                {
                    break;
                }
                var imported = 0;

                var strategy = import.DataSource.DataStrategy;
                var newData  = strategy.GetNewData();
                if (newData == null || newData.Rows.Count == 0)
                {
                    continue;
                }

                var parsers = import.Entity.Select(ent => ParserFactory.GetEntityParser(ent)).Where(parser => parser != null);

                foreach (var row in newData.Rows)
                {
                    if (connectionError)
                    {
                        break;
                    }
                    try
                    {
                        foreach (var parser in parsers)
                        {
                            var data = parser.Parse(row);

                            if (data.Operation == -1)
                            {
                                continue;
                            }

                            var encodedData = transform.Encode(data);

                            Logger.Info("Importing data with session: " + SessionToken);
                            var result = Server.Import.ImportData(SessionToken, ConfigImportClient.Company, ConfigImportClient.Branch, encodedData, data.Version);

                            if (!result.RespuestaOk && !IsSessionActive())
                            {
                                Logger.Info("Inactive session: " + SessionToken);
                                Login();
                                Logger.Info("Importing data with session: " + SessionToken);
                                result = Server.Import.ImportData(SessionToken, ConfigImportClient.Company, ConfigImportClient.Branch, encodedData, data.Version);
                            }

                            if (!result.RespuestaOk)
                            {
                                throw new ApplicationException(result.Mensaje);
                            }
                            imported++;
                        }
                    }
                    catch (Exception ex)
                    {
                        if (ex.GetType() == typeof(TimeoutException))
                        {
                            Logger.Error("Error de conexión. No se puede acceder al server.");
                            connectionError = true;
                        }
                        else
                        {
                            Logger.Error(ex);
                        }

                        // TODO: Guardar Registro como mal importado en archivo de errores para reprocesar (csv)
                    }
                }

                if (imported == 0 || connectionError)
                {
                    import.DataSource.DataStrategy.Revert();
                }
            }
        }
예제 #44
0
 public WpfAdvancedAdapter(IList<ISubject> subjects, IFieldPathComboBox pathCombo, IParameterBuilderFactory builderFactory, IControlFactory<System.Windows.UIElement> controlFactory, ParserFactory parserFactory)
     : base(subjects, pathCombo, builderFactory, controlFactory)
 {
     Parser = parserFactory;
 }
예제 #45
0
 /**
  *  This method is separate from {@link #parse1} so the first pass can be distinguished when analyzing
  *  profiler results.
  */
 protected void parse2(ParserFactory factory, IEnumerable<ICharStream> sources)
 {
     GC.Collect();
     parseSources(factory, sources);
 }