コード例 #1
0
        internal static ConstructorDeclarationSyntax GenerateConstructorDeclaration(
            IMethodSymbol constructor, CodeGenerationDestination destination, 
            Workspace workspace, CodeGenerationOptions options, ParseOptions parseOptions)
        {
            options = options ?? CodeGenerationOptions.Default;

            var reusableSyntax = GetReuseableSyntaxNodeForSymbol<ConstructorDeclarationSyntax>(constructor, options);
            if (reusableSyntax != null)
            {
                return reusableSyntax;
            }

            bool hasNoBody = !options.GenerateMethodBodies;

            var declaration = SyntaxFactory.ConstructorDeclaration(
                attributeLists: AttributeGenerator.GenerateAttributeLists(constructor.GetAttributes(), options),
                modifiers: GenerateModifiers(constructor, options),
                identifier: CodeGenerationConstructorInfo.GetTypeName(constructor).ToIdentifierToken(),
                parameterList: ParameterGenerator.GenerateParameterList(constructor.Parameters, isExplicit: false, options: options),
                initializer: GenerateConstructorInitializer(constructor),
                body: hasNoBody ? null : GenerateBlock(constructor),
                semicolonToken: hasNoBody ? SyntaxFactory.Token(SyntaxKind.SemicolonToken) : default(SyntaxToken));

            declaration = UseExpressionBodyIfDesired(workspace, declaration, parseOptions);

            return AddCleanupAnnotationsTo(
                ConditionallyAddDocumentationCommentTo(declaration, constructor, options));
        }
コード例 #2
0
        protected async Task TestBraceHighlightingAsync(string markup, ParseOptions options = null)
        {
            using (var workspace = await CreateWorkspaceAsync(markup, options))
            {
                WpfTestCase.RequireWpfFact($"{nameof(AbstractBraceHighlightingTests)}.{nameof(TestBraceHighlightingAsync)} creates asynchronous taggers");

                var provider = new BraceHighlightingViewTaggerProvider(
                    workspace.GetService<IBraceMatchingService>(),
                    workspace.GetService<IForegroundNotificationService>(),
                    AggregateAsynchronousOperationListener.EmptyListeners);

                var testDocument = workspace.Documents.First();
                var buffer = testDocument.TextBuffer;
                var document = buffer.CurrentSnapshot.GetRelatedDocumentsWithChanges().FirstOrDefault();
                var context = new TaggerContext<BraceHighlightTag>(
                    document, buffer.CurrentSnapshot,
                    new SnapshotPoint(buffer.CurrentSnapshot, testDocument.CursorPosition.Value));
                await provider.ProduceTagsAsync_ForTestingPurposesOnly(context);

                var expectedHighlights = testDocument.SelectedSpans.Select(ts => ts.ToSpan()).OrderBy(s => s.Start).ToList();
                var actualHighlights = context.tagSpans.Select(ts => ts.Span.Span).OrderBy(s => s.Start).ToList();

                Assert.Equal(expectedHighlights, actualHighlights);
            }
        }
コード例 #3
0
        /// <summary>
        /// Tries to parse the dataFields using the delimiter and fields. If true,
        /// result will hold an IStringConverter that can convert all valid input
        /// in the form of dataFields, only extracting fields.
        /// </summary>
        /// <param name="dataFields">Input string</param>
        /// <param name="delimiter">Seperator</param>
        /// <param name="fields">Required (conversion) fields</param>
        /// <param name="result">Converter</param>
        /// <param name="options">Parseoptions</param>
        /// <returns>Parse is possible</returns>
        public static Boolean TryParse(String dataFields, Char delimiter, String[] fields, out IStringConverter result, 
            ParseOptions options = ParseOptions.CleanupQuotes)
        {
            result = new DelimiterConverter(delimiter);

            var splittedDataFields = new Queue<String>(dataFields.Split(delimiter));
            var fieldsQueue = new Queue<String>(fields);

            while (fieldsQueue.Count > 0 && splittedDataFields.Count > 0)
            {
                var field = fieldsQueue.Peek();
                var data = splittedDataFields.Dequeue().Trim();

                if (options.HasFlag(ParseOptions.GlueStrings))
                    while (data.StartsWith("\"") && !data.EndsWith("\"") && splittedDataFields.Count > 0)
                        data = data + "," + splittedDataFields.Dequeue().Trim();

                if (options.HasFlag(ParseOptions.CleanupQuotes))
                    data = data.Replace("\"", "").Trim();

                (result as DelimiterConverter).PushMask(field == data);

                if (field == data)
                    fieldsQueue.Dequeue();
            }

            return fieldsQueue.Count == 0;
        }
コード例 #4
0
        private void Test(
            string markup,
            ParseOptions options,
            bool optionIsEnabled = true)
        {
            using (var workspace = CreateWorkspaceFromFile(markup, options))
            {
                var testDocument = workspace.Documents.Single();
                var expectedHighlightSpans = testDocument.SelectedSpans ?? new List<TextSpan>();
                expectedHighlightSpans = Sort(expectedHighlightSpans);
                var cursorSpan = testDocument.AnnotatedSpans["Cursor"].Single();
                var textSnapshot = testDocument.TextBuffer.CurrentSnapshot;
                var document = workspace.CurrentSolution.GetDocument(testDocument.Id);

                // If the position being tested is immediately following the keyword, 
                // we should get the token before this position to find the appropriate 
                // ancestor node.
                var highlighter = CreateHighlighter();

                var root = document.GetSyntaxRootAsync().Result;

                for (int i = 0; i <= cursorSpan.Length; i++)
                {
                    var position = cursorSpan.Start + i;
                    var highlightSpans = highlighter.GetHighlights(root, position, CancellationToken.None).ToList();
                    highlightSpans = Sort(highlightSpans);

                    CheckSpans(expectedHighlightSpans, highlightSpans);
                }
            }
        }
コード例 #5
0
 internal CompilationVerifier CompileAndVerify(
     string source,
     IEnumerable<MetadataReference> additionalRefs = null,
     IEnumerable<ModuleData> dependencies = null,
     Action<IModuleSymbol> sourceSymbolValidator = null,
     Action<PEAssembly> assemblyValidator = null,
     Action<IModuleSymbol> symbolValidator = null,
     SignatureDescription[] expectedSignatures = null,
     string expectedOutput = null,
     CompilationOptions options = null,
     ParseOptions parseOptions = null,
     bool verify = true)
 {
     return CompileAndVerify(
         sources: new string[] { source },
         additionalRefs: additionalRefs,
         dependencies: dependencies,
         sourceSymbolValidator: sourceSymbolValidator,
         assemblyValidator: assemblyValidator,
         symbolValidator: symbolValidator,
         expectedSignatures: expectedSignatures,
         expectedOutput: expectedOutput,
         options: options,
         parseOptions: parseOptions,
         verify: verify);
 }
コード例 #6
0
        internal CompilationVerifier CompileAndVerify(
            string[] sources,
            IEnumerable<MetadataReference> additionalRefs = null,
            IEnumerable<ModuleData> dependencies = null,
            Action<IModuleSymbol> sourceSymbolValidator = null,
            Action<PEAssembly> assemblyValidator = null,
            Action<IModuleSymbol> symbolValidator = null,
            SignatureDescription[] expectedSignatures = null,
            string expectedOutput = null,
            CompilationOptions options = null,
            ParseOptions parseOptions = null,
            bool verify = true)
        {
            if (options == null)
            {
                options = CompilationOptionsReleaseDll.WithOutputKind((expectedOutput != null) ? OutputKind.ConsoleApplication : OutputKind.DynamicallyLinkedLibrary);
            }

            var compilation = GetCompilationForEmit(sources, additionalRefs, options, parseOptions);

            return this.CompileAndVerify(
                compilation,
                null,
                dependencies,
                sourceSymbolValidator,
                assemblyValidator,
                symbolValidator,
                expectedSignatures,
                expectedOutput,
                verify);
        }
コード例 #7
0
        private static ConversionOperatorDeclarationSyntax GenerateConversionDeclarationWorker(
            IMethodSymbol method,
            CodeGenerationDestination destination,
            Workspace workspace,
            CodeGenerationOptions options,
            ParseOptions parseOptions)
        {
            var hasNoBody = !options.GenerateMethodBodies || method.IsExtern;

            var reusableSyntax = GetReuseableSyntaxNodeForSymbol<ConversionOperatorDeclarationSyntax>(method, options);
            if (reusableSyntax != null)
            {
                return reusableSyntax;
            }

            var operatorToken = SyntaxFactory.Token(SyntaxFacts.GetOperatorKind(method.MetadataName));
            var keyword = method.MetadataName == WellKnownMemberNames.ImplicitConversionName
                ? SyntaxFactory.Token(SyntaxKind.ImplicitKeyword)
                : SyntaxFactory.Token(SyntaxKind.ExplicitKeyword);

            var declaration = SyntaxFactory.ConversionOperatorDeclaration(
                attributeLists: AttributeGenerator.GenerateAttributeLists(method.GetAttributes(), options),
                modifiers: GenerateModifiers(method),
                implicitOrExplicitKeyword: keyword,
                operatorKeyword: SyntaxFactory.Token(SyntaxKind.OperatorKeyword),
                type: method.ReturnType.GenerateTypeSyntax(),
                parameterList: ParameterGenerator.GenerateParameterList(method.Parameters, isExplicit: false, options: options),
                body: hasNoBody ? null : StatementGenerator.GenerateBlock(method),
                semicolonToken: hasNoBody ? SyntaxFactory.Token(SyntaxKind.SemicolonToken) : new SyntaxToken());

            declaration = UseExpressionBodyIfDesired(workspace, declaration, parseOptions);

            return declaration;
        }
コード例 #8
0
ファイル: MethodGenerator.cs プロジェクト: XieShuquan/roslyn
        private static MethodDeclarationSyntax GenerateMethodDeclarationWorker(
            IMethodSymbol method, CodeGenerationDestination destination, 
            Workspace workspace, CodeGenerationOptions options, ParseOptions parseOptions)
        {
            var hasNoBody = !options.GenerateMethodBodies ||
                            destination == CodeGenerationDestination.InterfaceType ||
                            method.IsAbstract;

            var explicitInterfaceSpecifier = GenerateExplicitInterfaceSpecifier(method.ExplicitInterfaceImplementations);

            var returnType = method.ReturnsByRef
                ? method.ReturnType.GenerateRefTypeSyntax()
                : method.ReturnType.GenerateTypeSyntax();

            var methodDeclaration = SyntaxFactory.MethodDeclaration(
                attributeLists: GenerateAttributes(method, options, explicitInterfaceSpecifier != null),
                modifiers: GenerateModifiers(method, destination, options),
                returnType: returnType,
                explicitInterfaceSpecifier: explicitInterfaceSpecifier,
                identifier: method.Name.ToIdentifierToken(),
                typeParameterList: GenerateTypeParameterList(method, options),
                parameterList: ParameterGenerator.GenerateParameterList(method.Parameters, explicitInterfaceSpecifier != null, options),
                constraintClauses: GenerateConstraintClauses(method),
                body: hasNoBody ? null : StatementGenerator.GenerateBlock(method),
                expressionBody: default(ArrowExpressionClauseSyntax),
                semicolonToken: hasNoBody ? SyntaxFactory.Token(SyntaxKind.SemicolonToken) : new SyntaxToken());

            methodDeclaration = UseExpressionBodyIfDesired(workspace, methodDeclaration, parseOptions);

            return AddCleanupAnnotationsTo(methodDeclaration);
        }
コード例 #9
0
ファイル: Parser.cs プロジェクト: amarant/GraphQLSharp
 /// <summary>
 /// Initializes a new instance of the <see cref="Parser"/> class.
 /// Returns the parser object that is used to store state throughout the
 /// process of parsing.
 /// </summary>
 /// <param name="source">The source.</param>
 /// <param name="options">The options.</param>
 protected Parser(Source source, ParseOptions options)
 {
     Source = source;
     Options = options ?? new ParseOptions();
     _lexToken = new Lexer(source);
     PrevEnd = 0;
     Token = _lexToken.NextToken();
 }
コード例 #10
0
 /// <param name="files">Can pass in multiple file contents with individual source kind: files will be named test1.vb, test2.vbx, etc.</param>
 public static Task<TestWorkspace> CreateWorkspaceFromFilesAsync(
     string[] files,
     ParseOptions[] parseOptions = null,
     CompilationOptions compilationOptions = null,
     ExportProvider exportProvider = null)
 {
     return TestWorkspaceFactory.CreateWorkspaceFromFilesAsync(LanguageNames.VisualBasic, compilationOptions, parseOptions, files, exportProvider);
 }
コード例 #11
0
ファイル: AddUsingTests_NuGet.cs プロジェクト: CAPCHIK/roslyn
 protected override async Task<TestWorkspace> CreateWorkspaceFromFileAsync(string definition, ParseOptions parseOptions, CompilationOptions compilationOptions)
 {
     var workspace = await base.CreateWorkspaceFromFileAsync(definition, parseOptions, compilationOptions);
     workspace.Options = workspace.Options
         .WithChangedOption(AddImportOptions.SuggestForTypesInNuGetPackages, LanguageNames.CSharp, true)
         .WithChangedOption(AddImportOptions.SuggestForTypesInReferenceAssemblies, LanguageNames.CSharp, true);
     return workspace;
 }
コード例 #12
0
        public static async Task<ChangeSignatureTestState> CreateAsync(string markup, string languageName, ParseOptions parseOptions = null)
        {
            var workspace = languageName == LanguageNames.CSharp
                  ? await CSharpWorkspaceFactory.CreateWorkspaceFromFileAsync(markup, exportProvider: s_exportProvider, parseOptions: (CSharpParseOptions)parseOptions)
                  : await VisualBasicWorkspaceFactory.CreateWorkspaceFromFileAsync(markup, exportProvider: s_exportProvider, parseOptions: parseOptions, compilationOptions: new VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary));

            return new ChangeSignatureTestState(workspace);
        }
コード例 #13
0
        public override void WriteTo(ParseOptions options, ObjectWriter writer, CancellationToken cancellationToken)
        {
            WriteParseOptionsTo(options, writer, cancellationToken);

            var csharpOptions = (CSharpParseOptions)options;
            writer.WriteInt32((int)csharpOptions.LanguageVersion);
            writer.WriteValue(options.PreprocessorSymbolNames.ToArray());
        }
コード例 #14
0
 /// <summary>
 /// Creates a single buffer in a workspace.
 /// </summary>
 /// <param name="content">Lines of text, the buffer contents</param>
 internal static Task<TestWorkspace> CreateWorkspaceFromFileAsync(
     string language,
     CompilationOptions compilationOptions,
     ParseOptions parseOptions,
     string content)
 {
     return CreateWorkspaceFromFilesAsync(language, compilationOptions, parseOptions, new[] { content });
 }
コード例 #15
0
 /// <summary>
 /// Creates a single buffer in a workspace.
 /// </summary>
 /// <param name="content">Lines of text, the buffer contents</param>
 internal static TestWorkspace CreateWorkspaceFromLines(
     string language,
     CompilationOptions compilationOptions,
     ParseOptions parseOptions,
     params string[] content)
 {
     var total = content.Join(Environment.NewLine);
     return CreateWorkspaceFromFiles(language, compilationOptions, parseOptions, total);
 }
コード例 #16
0
 public static Task<TestWorkspace> CreateWorkspaceFromFileAsync(
     string file,
     ParseOptions parseOptions = null,
     CompilationOptions compilationOptions = null,
     ExportProvider exportProvider = null,
     string[] metadataReferences = null)
 {
     return CreateWorkspaceFromFilesAsync(new[] { file }, parseOptions, compilationOptions, exportProvider, metadataReferences);
 }
コード例 #17
0
 internal async Task TestWithAccessorCodeStyleOptionsOnAsync(
     string initialMarkup, string expectedMarkup,
     int index = 0, bool compareTokens = true,
     ParseOptions parseOptions = null,
     bool withScriptOption = false)
 {
     await TestAsync(initialMarkup, expectedMarkup, parseOptions, null,
         index, compareTokens, options: AccessorOptionsOn, withScriptOption: withScriptOption);
 }
コード例 #18
0
 /// <summary>
 /// Creates a single buffer in a workspace.
 /// </summary>
 /// <param name="content">Lines of text, the buffer contents</param>
 internal static Task<TestWorkspace> CreateAsync(
     string workspaceKind,
     string language,
     CompilationOptions compilationOptions,
     ParseOptions parseOptions,
     string content)
 {
     return CreateAsync(workspaceKind, language, compilationOptions, parseOptions, new[] { content });
 }
コード例 #19
0
        private static XAttribute CreateFeaturesAttribute(ParseOptions parseOptions)
        {
            if (parseOptions.Features == null || parseOptions.Features.Count == 0)
            {
                return null;
            }

            var value = string.Join(";", parseOptions.Features.Select(p => $"{p.Key}={p.Value}"));
            return new XAttribute(FeaturesAttributeName, value);
        }
コード例 #20
0
 protected void AssertFormat(
     string expected,
     string code,
     bool debugMode = false,
     Dictionary<OptionKey, object> changedOptionSet = null,
     bool testWithTransformation = true,
     ParseOptions parseOptions = null)
 {
     AssertFormat(expected, code, SpecializedCollections.SingletonEnumerable(new TextSpan(0, code.Length)), debugMode, changedOptionSet, testWithTransformation, parseOptions);
 }
コード例 #21
0
 internal static ConversionOperatorDeclarationSyntax GenerateConversionDeclaration(
     IMethodSymbol method,
     CodeGenerationDestination destination,
     Workspace workspace,
     CodeGenerationOptions options,
     ParseOptions parseOptions)
 {
     var declaration = GenerateConversionDeclarationWorker(method, destination, workspace, options, parseOptions);
     return AddCleanupAnnotationsTo(AddAnnotationsTo(method,
         ConditionallyAddDocumentationCommentTo(declaration, method, options)));
 }
コード例 #22
0
 protected void AssertFormat(
     string expected,
     string code,
     IEnumerable<TextSpan> spans,
     bool debugMode = false,
     Dictionary<OptionKey, object> changedOptionSet = null,
     bool testWithTransformation = true,
     ParseOptions parseOptions = null)
 {
     AssertFormat(expected, code, spans, LanguageNames.CSharp, debugMode, changedOptionSet, testWithTransformation, parseOptions);
 }
コード例 #23
0
ファイル: RudeEditTestBase.cs プロジェクト: elemk0vv/roslyn-1
        internal static EditScript<SyntaxNode> GetTopEdits(string src1, string src2, ParseOptions options = null)
        {
            var tree1 = ParseSource(src1, options: options);
            var tree2 = ParseSource(src2, options: options);

            tree1.GetDiagnostics().Verify();
            tree2.GetDiagnostics().Verify();

            var match = TopSyntaxComparer.Instance.ComputeMatch(tree1.GetRoot(), tree2.GetRoot());
            return match.GetTreeEdits();
        }
コード例 #24
0
 private static XAttribute CreateDocumentationModeAttribute(ParseOptions parseOptions)
 {
     if (parseOptions == null)
     {
         return null;
     }
     else
     {
         return new XAttribute(DocumentationModeAttributeName, parseOptions.DocumentationMode);
     }
 }
コード例 #25
0
 //TODO: 4.6 should be the default for most testcases
 //      for now I do not want to do such a large change at once
 //      when 4.6 is the default, this override and ExpressionAssemblyRef below will not be needed.
 protected override Compilation GetCompilationForEmit(
     IEnumerable<string> source,
     IEnumerable<MetadataReference> additionalRefs,
     CompilationOptions options,
     ParseOptions parseOptions)
 {
     return CreateCompilationWithMscorlib46(
         Parse(source, options: (CSharpParseOptions)parseOptions),
         references: additionalRefs,
         options: (CSharpCompilationOptions)options,
         assemblyName: GetUniqueName());
 }
コード例 #26
0
        public void TestChangeSignatureViaCommand(
            string languageName,
            string markup,
            bool expectedSuccess = true,
            int[] updatedSignature = null,
            string expectedUpdatedInvocationDocumentCode = null,
            string expectedErrorText = null,
            int? totalParameters = null,
            bool verifyNoDiagnostics = false,
            ParseOptions parseOptions = null)
        {
            using (var testState = new ChangeSignatureTestState(markup, languageName, parseOptions))
            {
                testState.TestChangeSignatureOptionsService.IsCancelled = false;
                testState.TestChangeSignatureOptionsService.UpdatedSignature = updatedSignature;
                var result = testState.ChangeSignature();

                if (expectedSuccess)
                {
                    Assert.True(result.Succeeded);
                    Assert.Null(testState.ErrorMessage);
                }
                else
                {
                    Assert.False(result.Succeeded);

                    if (expectedErrorText != null)
                    {
                        Assert.Equal(expectedErrorText, testState.ErrorMessage);
                        Assert.Equal(NotificationSeverity.Error, testState.ErrorSeverity);
                    }
                }

                // Allow testing of invocation document regardless of success/failure
                if (expectedUpdatedInvocationDocumentCode != null)
                {
                    var updatedInvocationDocument = result.UpdatedSolution.GetDocument(testState.InvocationDocument.Id);
                    var updatedCode = updatedInvocationDocument.GetTextAsync(CancellationToken.None).Result.ToString();
                    Assert.Equal(expectedUpdatedInvocationDocumentCode, updatedCode);
                }

                if (verifyNoDiagnostics)
                {
                    var diagnostics = testState.InvocationDocument.GetSemanticModelAsync().Result.GetDiagnostics();

                    if (diagnostics.Length > 0)
                    {
                        Assert.True(false, CreateDiagnosticsString(diagnostics, updatedSignature, totalParameters, testState.InvocationDocument.GetTextAsync().Result.ToString()));
                    }
                }
            }
        }
コード例 #27
0
            public override SyntaxTree CreateRecoverableTree(string filePath, ParseOptions options, ValueSource<TextAndVersion> text, SyntaxNode root, bool reparse)
            {
                options = options ?? GetDefaultParseOptions();

                if (reparse)
                {
                    return new ReparsedSyntaxTree(this, filePath, (CSharpParseOptions)options, text, (CompilationUnitSyntax)root);
                }
                else
                {
                    return new SerializedSyntaxTree(this, filePath, (CSharpParseOptions)options, text, (CompilationUnitSyntax)root);
                }
            }
コード例 #28
0
        protected void TestMissing(string initialMarkup, ParseOptions parseOptions, CompilationOptions compilationOptions, IDictionary<OptionKey, object> options = null, string fixAllActionEquivalenceKey = null)
        {
            using (var workspace = CreateWorkspaceFromFile(initialMarkup, parseOptions, compilationOptions))
            {
                if (options != null)
                {
                    ApplyOptionsToWorkspace(options, workspace);
                }

                var diagnostics = GetDiagnosticAndFix(workspace, fixAllActionEquivalenceKey);
                Assert.False(diagnostics?.Item2?.Fixes.IsEmpty == true);
            }
        }
コード例 #29
0
 protected void Test(
     string initial,
     string expected,
     ParseOptions parseOptions,
     int index = 0,
     bool compareTokens = true,
     bool isLine = true,
     IDictionary<OptionKey, object> options = null,
     bool isAddedDocument = false,
     string fixAllActionEquivalenceKey = null)
 {
     Test(initial, expected, parseOptions, null, index, compareTokens, isLine, options, isAddedDocument, fixAllActionEquivalenceKey);
 }
コード例 #30
0
        /// <summary>
        /// Generates Transact-SQL batches, suitable for execution, from the text of a 
        /// Transact-SQL script.
        /// </summary>
        /// <param name="scriptSql">Transact-SQL script text</param>
        /// <returns>Collection of Batch objects for each batch in the supplied script</returns>
        public static IEnumerable<Batch> GetBatches(string scriptSql)
        {
            /* This method could be rewritten to use the new `Parser.ParseSql` class method. */

            ParseOptions parseOptions = new ParseOptions();
            Scanner scanner = new Scanner(parseOptions);

            int state = 0,
                start,
                end,
                lastTokenEnd = -1,
                token;

            bool isPairMatch, isExecAutoParamHelp;

            List<Batch> batches = new List<Batch>();
            StringBuilder nextBatchSql = new StringBuilder();

            scanner.SetSource(scriptSql, 0);

            while ((token = scanner.GetNext(ref state, out start, out end, out isPairMatch, out isExecAutoParamHelp)) != (int)Tokens.EOF)
            {
                if ((Tokens)token == Tokens.LEX_BATCH_SEPERATOR)
                {
                    nextBatchSql.Append(scriptSql.Substring(lastTokenEnd + 1, start - lastTokenEnd + 1 - 1 - 1));
                    batches.Add(new Batch(nextBatchSql.ToString()));
            #if NET35
                    nextBatchSql = new StringBuilder();
            #else
                    nextBatchSql.Clear();
            #endif
                }
                else
                {
                    nextBatchSql.Append(scriptSql.Substring(lastTokenEnd + 1, end - lastTokenEnd + 1 - 1));
                }

                lastTokenEnd = end;
            }

            #if NET35
            if (!String.IsNullOrEmpty(nextBatchSql.ToString().Trim()))
            #else
            if (!String.IsNullOrWhiteSpace(nextBatchSql.ToString()))
            #endif
                batches.Add(new Batch(nextBatchSql.ToString()));

            return batches;
        }
コード例 #31
0
        public static Project CreateReferenceOnlyProjectFromAnyOptions(this Project project, CompilationOptions baseOptions, ParseOptions parseOptions)
        {
            var options           = baseOptions.WithMetadataImportOptions(MetadataImportOptions.All);
            var viewerId          = ProjectId.CreateNewId();
            var projectReferences = project.ProjectReferences.Concat(new[] { new ProjectReference(project.Id) });
            var viewerProjectInfo = project.ToProjectInfo(viewerId, project.Name + viewerId, options,
                                                          projectReferences, parseOptions);
            var csharpViewOfVbProject = project.Solution.AddProject(viewerProjectInfo).GetProject(viewerId);

            return(csharpViewOfVbProject);
        }
コード例 #32
0
            public HostProject(Workspace workspace, SolutionId solutionId, string languageName, ParseOptions parseOptionsOpt, CompilationOptions compilationOptionsOpt, IEnumerable <MetadataReference> metadataReferences)
            {
                Debug.Assert(workspace != null);
                Debug.Assert(languageName != null);
                Debug.Assert(metadataReferences != null);

                _workspace             = workspace;
                _parseOptionsOpt       = parseOptionsOpt;
                _compilationOptionsOpt = compilationOptionsOpt;

                Id       = ProjectId.CreateNewId(debugName: "Miscellaneous Files");
                Language = languageName;

                // the assembly name must be unique for each collection of loose files.  since the name doesn't matter
                // a random GUID can be used.
                _assemblyName = Guid.NewGuid().ToString("N");

                _version            = VersionStamp.Create();
                _metadataReferences = metadataReferences;
            }
コード例 #33
0
        public static Project ToProjectFromAnyOptions(this Project project, CompilationOptions compilationOptions, ParseOptions parseOptions)
        {
            // Use a new id to workaround VS caching issue first reported here: https://github.com/icsharpcode/CodeConverter/issues/586
            var newProjectId = ProjectId.CreateNewId("ConvertedProject");
            var projectInfo  = project.ToProjectInfo(newProjectId, project.Name, compilationOptions,
                                                     project.ProjectReferences, parseOptions);
            var convertedSolution = project.Solution.RemoveProject(project.Id).AddProject(projectInfo);

            return(convertedSolution.GetProject(newProjectId));
        }
コード例 #34
0
        private static OperatorDeclarationSyntax UseExpressionBodyIfDesired(
            CodeGenerationOptions options, OperatorDeclarationSyntax operatorDeclaration, ParseOptions parseOptions)
        {
            if (operatorDeclaration.ExpressionBody == null)
            {
                var expressionBodyPreference = options.Options.GetOption(CSharpCodeStyleOptions.PreferExpressionBodiedMethods).Value;
                if (operatorDeclaration.Body.TryConvertToArrowExpressionBody(
                        operatorDeclaration.Kind(), parseOptions, expressionBodyPreference,
                        out var expressionBody, out var semicolonToken))
                {
                    return(operatorDeclaration.WithBody(null)
                           .WithExpressionBody(expressionBody)
                           .WithSemicolonToken(semicolonToken));
                }
            }

            return(operatorDeclaration);
        }
コード例 #35
0
 protected override Task <TestWorkspace> CreateWorkspaceFromCodeAsync(string code, ParseOptions options)
 {
     return(TestWorkspace.CreateCSharpAsync(code, options));
 }
コード例 #36
0
 public abstract void WriteTo(ParseOptions options, ObjectWriter writer);
コード例 #37
0
 private Task <ParseResult> startParse(int curId, string text, bool doTranslation, ParseOptions parseOptions)
 {
     return(Task.Factory.StartNew(() => {
         try {
             var parseData = Edict.instance.parse(text, parseOptions);
             if (parseData != null)
             {
                 parseData.id = curId;
                 if (doTranslation)
                 {
                     sendTranslationRequest(curId, parseData);
                 }
                 parseCacheEntries.Enqueue(curId);
                 if (parseCacheEntries.Count > MAX_CACHE)
                 {
                     int res;
                     if (parseCacheEntries.TryDequeue(out res))
                     {
                         ParseResult unused;
                         parseCache.TryRemove(res, out unused);
                     }
                 }
                 parseCache[curId] = parseData;
                 if (onEdictDone != null && (Settings.app.translationDisplay == TranslationDisplay.PARSE || Settings.app.translationDisplay == TranslationDisplay.BOTH))
                 {
                     onEdictDone(curId, parseData);
                 }
             }
             return parseData;
         } catch (Exception e) {
             Logger.logException(e);
             return null;
         }
     }));
 }
コード例 #38
0
ファイル: PhpSyntaxTree.cs プロジェクト: jdluzen/peachpie
 public override SyntaxTree WithRootAndOptions(SyntaxNode root, ParseOptions options)
 {
     throw new NotImplementedException();
 }
コード例 #39
0
 /// <summary>Creates an <code>XMPMeta</code>-object from a byte-buffer.</summary>
 /// <seealso cref="Parse(InputStream, Com.Adobe.Xmp.Options.ParseOptions)"/>
 /// <param name="buffer">a String contain an XMP-file.</param>
 /// <param name="options">Options controlling the parsing.</param>
 /// <returns>Returns the <code>XMPMeta</code>-object created from the input.</returns>
 /// <exception cref="XMPException">If the file is not well-formed XML or if the parsing fails.</exception>
 /// <exception cref="Com.Adobe.Xmp.XMPException"/>
 public static XMPMeta ParseFromBuffer(sbyte[] buffer, ParseOptions options)
 {
     return(XMPMetaParser.Parse(buffer, options));
 }
コード例 #40
0
 /// <summary>
 /// These functions support parsing serialized RDF into an XMP object, and serailizing an XMP
 /// object into RDF.
 /// </summary>
 /// <remarks>
 /// These functions support parsing serialized RDF into an XMP object, and serailizing an XMP
 /// object into RDF. The input for parsing may be any valid Unicode
 /// encoding. ISO Latin-1 is also recognized, but its use is strongly discouraged. Serialization
 /// is always as UTF-8.
 /// <p>
 /// <code>ParseFromBuffer()</code> parses RDF from an <code>InputStream</code>. The encoding
 /// is recognized automatically.
 /// </remarks>
 /// <param name="in">an <code>InputStream</code></param>
 /// <param name="options">
 /// Options controlling the parsing.<br />
 /// The available options are:
 /// <ul>
 /// <li> XMP_REQUIRE_XMPMETA - The &lt;x:xmpmeta&gt; XML element is required around
 /// <tt>&lt;rdf:RDF&gt;</tt>.
 /// <li> XMP_STRICT_ALIASING - Do not reconcile alias differences, throw an exception.
 /// </ul>
 /// <em>Note:</em>The XMP_STRICT_ALIASING option is not yet implemented.
 /// </param>
 /// <returns>Returns the <code>XMPMeta</code>-object created from the input.</returns>
 /// <exception cref="XMPException">If the file is not well-formed XML or if the parsing fails.</exception>
 /// <exception cref="Com.Adobe.Xmp.XMPException"/>
 public static XMPMeta Parse(InputStream @in, ParseOptions options)
 {
     return(XMPMetaParser.Parse(@in, options));
 }
コード例 #41
0
 protected override bool IsSupported(SyntaxKind assignmentKind, ParseOptions options)
 => assignmentKind != SyntaxKind.CoalesceExpression ||
 ((CSharpParseOptions)options).LanguageVersion >= LanguageVersion.CSharp8;
コード例 #42
0
ファイル: CrontabSchedule.cs プロジェクト: uatec/NCrontab
 public static CrontabSchedule TryParse(string expression, ParseOptions options) =>
 TryParse(expression ?? string.Empty, options, v => v, _ => null);
コード例 #43
0
 public TestParameters WithParseOptions(ParseOptions parseOptions)
     => new TestParameters(parseOptions, compilationOptions, options, fixProviderData, index, priority, retainNonFixableDiagnostics, includeDiagnosticsOutsideSelection, title);
コード例 #44
0
 internal static SyntaxNode GetSyntaxRoot(string expectedText, string language, ParseOptions options = null)
 {
     if (language == LanguageNames.CSharp)
     {
         return(CS.SyntaxFactory.ParseCompilationUnit(expectedText, options: (CS.CSharpParseOptions)options));
     }
     else
     {
         return(VB.SyntaxFactory.ParseCompilationUnit(expectedText, options: (VB.VisualBasicParseOptions)options));
     }
 }
コード例 #45
0
 protected override bool IsApplicableToLanguageVersion(ParseOptions options)
 {
     return(((CSharpParseOptions)options).LanguageVersion >= LanguageVersion.CSharp6);
 }
コード例 #46
0
 protected abstract bool ShouldAnalyze(ParseOptions options);
コード例 #47
0
 protected override PropertyDeclarationSyntax WithGenerateBody(
     SemanticModel semanticModel, PropertyDeclarationSyntax declaration,
     OptionSet options, ParseOptions parseOptions)
 {
     return(WithAccessorList(semanticModel, declaration, options, parseOptions));
 }
コード例 #48
0
 public TestParameters WithParseOptions(ParseOptions parseOptions)
 => new TestParameters(parseOptions, compilationOptions, options, fixAllActionEquivalenceKey, fixProviderData);
コード例 #49
0
 private static TestWorkspace CreateWorkspaceFromFile(string file, bool isVisualBasic, ParseOptions parseOptions, CompilationOptions compilationOptions)
 {
     return(isVisualBasic ?
            VisualBasicWorkspaceFactory.CreateWorkspaceFromFile(file, (VB.VisualBasicParseOptions)parseOptions, (VB.VisualBasicCompilationOptions)compilationOptions) :
            CSharpWorkspaceFactory.CreateWorkspaceFromFile(file, (CS.CSharpParseOptions)parseOptions, (CS.CSharpCompilationOptions)compilationOptions));
 }
コード例 #50
0
 /// <summary>Creates an <code>XMPMeta</code>-object from a string.</summary>
 /// <seealso cref="ParseFromString(string, Com.Adobe.Xmp.Options.ParseOptions)"/>
 /// <param name="packet">a String contain an XMP-file.</param>
 /// <param name="options">Options controlling the parsing.</param>
 /// <returns>Returns the <code>XMPMeta</code>-object created from the input.</returns>
 /// <exception cref="XMPException">If the file is not well-formed XML or if the parsing fails.</exception>
 /// <exception cref="Com.Adobe.Xmp.XMPException"/>
 public static XMPMeta ParseFromString(string packet, ParseOptions options)
 {
     return(XMPMetaParser.Parse(packet, options));
 }
コード例 #51
0
 protected override Task <TestWorkspace> CreateWorkspaceFromFileAsync(string definition, ParseOptions parseOptions, CompilationOptions compilationOptions)
 {
     return(TestWorkspace.CreateCSharpAsync(definition, (CSharpParseOptions)parseOptions, (CSharpCompilationOptions)compilationOptions));
 }
コード例 #52
0
 protected abstract Task <ImmutableArray <ClassifiedSpan> > GetClassificationSpansAsync(
     string text,
     TextSpan span,
     ParseOptions parseOptions,
     TestHost testHost
     );
コード例 #53
0
 public void OnOptionsChanged(ProjectId projectId, CompilationOptions compilationOptions, ParseOptions parseOptions)
 {
 }
コード例 #54
0
        async Task InitializeAsync(ITextBuffer buffer, string code, MetadataReference[] refs, string languageName, ISynchronousTagger <IClassificationTag> tagger, CompilationOptions compilationOptions, ParseOptions parseOptions)
        {
            using (var workspace = new AdhocWorkspace(RoslynMefHostServices.DefaultServices)) {
                var documents = new List <DocumentInfo>();
                var projectId = ProjectId.CreateNewId();
                documents.Add(DocumentInfo.Create(DocumentId.CreateNewId(projectId), "main.cs", null, SourceCodeKind.Regular, TextLoader.From(buffer.AsTextContainer(), VersionStamp.Create())));

                var projectInfo = ProjectInfo.Create(projectId, VersionStamp.Create(), "compilecodeproj", Guid.NewGuid().ToString(), languageName,
                                                     compilationOptions: compilationOptions
                                                     .WithOptimizationLevel(OptimizationLevel.Release)
                                                     .WithPlatform(Platform.AnyCpu)
                                                     .WithAssemblyIdentityComparer(DesktopAssemblyIdentityComparer.Default),
                                                     parseOptions: parseOptions,
                                                     documents: documents,
                                                     metadataReferences: refs,
                                                     isSubmission: false, hostObjectType: null);
                workspace.AddProject(projectInfo);
                foreach (var doc in documents)
                {
                    workspace.OpenDocument(doc.Id);
                }

                buffer.Replace(new Span(0, buffer.CurrentSnapshot.Length), code);

                {
                    // Initialize classification code paths
                    var spans = new NormalizedSnapshotSpanCollection(new SnapshotSpan(buffer.CurrentSnapshot, 0, buffer.CurrentSnapshot.Length));
                    foreach (var tagSpan in tagger.GetTags(spans, CancellationToken.None))
                    {
                    }
                }

                {
                    // Initialize completion code paths
                    var info = CompletionInfo.Create(buffer.CurrentSnapshot);
                    Debug.Assert(info != null);
                    if (info != null)
                    {
                        var completionTrigger = CompletionTrigger.Default;
                        var completionList    = await info.Value.CompletionService.GetCompletionsAsync(info.Value.Document, 0, completionTrigger);
                    }
                }

                {
                    // Initialize signature help code paths
                    var info = SignatureHelpInfo.Create(buffer.CurrentSnapshot);
                    Debug.Assert(info != null);
                    if (info != null)
                    {
                        int sigHelpIndex = code.IndexOf("sighelp");
                        Debug.Assert(sigHelpIndex >= 0);
                        var triggerInfo = new SignatureHelpTriggerInfo(SignatureHelpTriggerReason.InvokeSignatureHelpCommand);
                        var items       = await info.Value.SignatureHelpService.GetItemsAsync(info.Value.Document, sigHelpIndex, triggerInfo);
                    }
                }

                {
                    // Initialize quick info code paths
                    var info = QuickInfoState.Create(buffer.CurrentSnapshot);
                    Debug.Assert(info != null);
                    if (info != null)
                    {
                        int quickInfoIndex = code.IndexOf("Equals");
                        Debug.Assert(quickInfoIndex >= 0);
                        var item = await info.Value.QuickInfoService.GetItemAsync(info.Value.Document, quickInfoIndex);
                    }
                }
            }
        }
コード例 #55
0
 internal abstract bool SupportsPatterns(ParseOptions options);
コード例 #56
0
 protected abstract bool IsApplicableToLanguageVersion(ParseOptions options);
コード例 #57
0
        public static 块作用域 Parse_块作用域(char[] chars, int beginIndex, int endIndex, ParseOptions option, out int j)
        {
            j = -1;

            块作用域 块 = new 块作用域();

            StrSpan span = StrUtil.Trim(chars, beginIndex, endIndex, Parser._whiteSpaces);

            if (span.isEmpty)
            {
                return(块);
            }

            //int j;

            //List<语句> list语句 = new List<语句>();


            for (int i = span.iLeft; ; i = j + 1)
            {
                span = StrUtil.Trim(chars, i, span.iRight, Parser._whiteSpaces);

                if (span.isEmpty)
                {
                    break;
                }
                //if (Check_变量类型_KeyWord(chars, i, 代码段.iRight, "int"))
                //{
                //    语句 = Parse_变量声明和赋值_语句(chars, i, 代码段.iRight, "int", out j, list变量声明);
                //}
                //else if (Check_变量类型_KeyWord(chars, i, 代码段.iRight, "float"))
                //{
                //    语句 = Parse_变量声明和赋值_语句(chars, i, 代码段.iRight, "float", out j, list变量声明);
                //}
                //else if (Check_变量类型_KeyWord(chars, i, 代码段.iRight, "double"))
                //{
                //    语句 = Parse_变量声明和赋值_语句(chars, i, 代码段.iRight, "double", out j, list变量声明);
                //}
                //else if (Check_变量类型_KeyWord(chars, i, 代码段.iRight, "char"))
                //{
                //    语句 = Parse_变量声明和赋值_语句(chars, i, 代码段.iRight, "char", out j, list变量声明);
                //}
                //if (Check_if_while_KeyWord(chars, i, 代码段.iRight, "if"))
                //{
                //    语句 = Parse_if_语句(chars, i, 代码段.iRight, out j, list变量声明);
                //}
                //else if (Check_if_while_KeyWord(chars, i, 代码段.iRight, "while"))
                //{
                //    语句 = Parse_while_语句(chars, i, 代码段.iRight, out j, list变量声明);
                //}
                //else if (Check_return_KeyWord(chars, i, 代码段.iRight))
                //{
                //    语句 = Parse_return_语句(chars, i, 代码段.iRight, out j, list变量声明);
                //}
                //else if (Check_变量声明(chars, i, 代码段.iRight, out 变量类型))
                //{
                //    语句 = Parse_变量声明和赋值_语句(chars, i, 代码段.iRight, 变量类型, out j, list变量声明);
                //}
                //else
                //{
                //    语句 = Parse_表达式_语句(chars, i, 代码段.iRight, out j, list变量声明);
                //}

                if_语句 if_语句 = if_语句_Parser.Parse(chars, span.iLeft, span.iRight, out j);

                if (if_语句 != null)
                {
                    if_语句.Set_作用域(块);

                    块.list语句.Add(if_语句);

                    continue;
                }

                while_语句 while_语句 = while_语句_Parser.Parse(chars, span.iLeft, span.iRight, out j);

                if (while_语句 != null)
                {
                    while_语句.Set_作用域(块);

                    块.list语句.Add(while_语句);

                    continue;
                }

                for_语句 for_语句 = for_语句_Parser.Parse(chars, span.iLeft, span.iRight, out j);

                if (for_语句 != null)
                {
                    for_语句.Set_作用域(块);

                    块.list语句.Add(for_语句);

                    continue;
                }

                break_语句 break_语句 = Parse_break_语句(chars, span.iLeft, span.iRight, out j);

                if (break_语句 != null)
                {
                    break_语句.Set_作用域(块);

                    块.list语句.Add(break_语句);

                    continue;
                }

                return_语句 return_语句 = Parse_return_语句(chars, span.iLeft, span.iRight, out j);

                if (return_语句 != null)
                {
                    return_语句.Set_作用域(块);

                    块.list语句.Add(return_语句);

                    continue;
                }

                continue_语句 continue_语句 = Parse_continue_语句(chars, span.iLeft, span.iRight, out j);

                if (continue_语句 != null)
                {
                    continue_语句.Set_作用域(块);

                    块.list语句.Add(continue_语句);

                    continue;
                }

                变量声明和初始化语句 变量声明语句 = Parse_变量声明和初始化_语句(chars, span.iLeft, span.iRight, out j);

                if (变量声明语句 != null)
                {
                    变量声明和初始化 变量声明 = 变量声明语句.变量声明;

                    块.Add_变量定义(变量声明, chars);
                    //if (块.dic变量声明.ContainsKey(变量声明.name))
                    //    throw new 语法错误_Exception("在当前作用域范围内已定义了名为 \"" + 变量声明.name + "\" 的变量 。", chars, 变量声明.变量名位置);

                    //变量声明语句.Set_作用域(块);

                    //块.dic变量声明.Add(变量声明.name, 变量声明);

                    // 变量声明和初始化 已经添加到作用域(块),所以这里不用把 变量声明语句 添加到 块,
                    // 甚至,都不需要 变量声明语句 这个对象,也不需要 变量声明和初始化语句 这个类
                    // 但为了 还原_C_源代码(),还是要把 变量声明语句 添加到 块
                    块.list语句.Add(变量声明语句);

                    continue;
                }


                表达式语句 表达式语句 = Parse_表达式语句(chars, span.iLeft, span.iRight, out j);

                if (表达式语句 != null)
                {
                    表达式语句.Set_作用域(块);

                    块.list语句.Add(表达式语句);
                }



                if (option == ParseOptions.Parse_第一个语句)
                {
                    break;
                }
            }

            return(块);
        }
コード例 #58
0
 public void SetParseOptions(ProjectId projectId, ParseOptions parseOptions)
 {
     OnParseOptionsChanged(projectId, parseOptions);
 }
コード例 #59
0
 protected abstract TestWorkspace CreateWorkspaceFromFile(string definition, ParseOptions parseOptions, CompilationOptions compilationOptions);
コード例 #60
0
 protected override TestWorkspace CreateWorkspaceFromFile(string definition, ParseOptions parseOptions, CompilationOptions compilationOptions)
 {
     return(CSharpWorkspaceFactory.CreateWorkspaceFromFile(definition, (CSharpParseOptions)parseOptions, (CSharpCompilationOptions)compilationOptions));
 }