public PathSyntaxReference(SyntaxNode node) { _tree = node.SyntaxTree; _kind = node.Kind(); _textSpan = node.Span; _pathFromRoot = ComputePathFromRoot(node); }
private IEnumerable<OutliningSpan> GetRegions(SyntaxTree syntaxTree, SyntaxTrivia trivia) { var outliner = new DisabledTextTriviaOutliner(); var spans = new List<OutliningSpan>(); outliner.CollectOutliningSpans(syntaxTree, trivia, spans, CancellationToken.None); return spans; }
/// <summary> /// Determine the classification type for a given token. /// </summary> /// <param name="classificationTypes">A classification service to retrieve classification types.</param> /// <param name="token">The token.</param> /// <param name="syntaxTree">The tree containing the token (can be null for tokens that are /// unparented).</param> /// <returns>The correct syntactic classification for the token.</returns> public static IClassificationType GetClassificationForToken(this IClassificationTypes classificationTypes, SyntaxToken token, SyntaxTree syntaxTree) { if (SyntaxFacts.IsKeywordKind(token.Kind)) { return classificationTypes.Keyword; } else if (token.Kind.IsPunctuation()) { return GetClassificationForPunctuation(classificationTypes, token); } else if (token.Kind == SyntaxKind.IdentifierToken) { return GetClassificationForIdentifer(classificationTypes, token, syntaxTree); } else if (token.Kind == SyntaxKind.StringLiteralToken || token.Kind == SyntaxKind.CharacterLiteralToken) { return token.IsVerbatimStringLiteral() ? classificationTypes.VerbatimStringLiteral : classificationTypes.StringLiteral; } else if (token.Kind == SyntaxKind.NumericLiteralToken) { return classificationTypes.NumericLiteral; } return null; }
private static IClassificationType GetClassificationForIdentifer(IClassificationTypes classificationTypes, SyntaxToken token, SyntaxTree syntaxTree) { if (token.Parent is TypeDeclarationSyntax && ((token.Parent as TypeDeclarationSyntax).Identifier == token)) { return GetClassificationForTypeDeclarationIdentifier(classificationTypes, token); } else if (token.Parent is EnumDeclarationSyntax && (token.Parent as EnumDeclarationSyntax).Identifier == token) { return classificationTypes.EnumTypeName; } else if (token.Parent is DelegateDeclarationSyntax && (token.Parent as DelegateDeclarationSyntax).Identifier == token) { return classificationTypes.DelegateTypeName; } else if (token.Parent is TypeParameterSyntax && (token.Parent as TypeParameterSyntax).Identifier == token) { return classificationTypes.TypeParameterName; } else if (syntaxTree != null && (syntaxTree.IsActualContextualKeyword(token) || syntaxTree.CouldBeVarKeywordInDeclaration(token))) { return classificationTypes.Keyword; } else { return classificationTypes.Identifier; } }
protected override AbstractIndenter GetIndenter( ISyntaxFactsService syntaxFacts, SyntaxTree syntaxTree, TextLine lineToBeIndented, IEnumerable<IFormattingRule> formattingRules, OptionSet optionSet, CancellationToken cancellationToken) { return new Indenter( syntaxFacts, syntaxTree, formattingRules, optionSet, lineToBeIndented, cancellationToken); }
public expression_node visit(SyntaxTree.expression expr) { expr.visit(syntax_tree_visitor); /*addressed_expression ad = ret_semantic as addressed_expression; if (ad != null && ad.is_addressed) { if (convertion_data_and_alghoritms.check_for_constant(ad)) ad.is_addressed = false; }*/ //Надеюсь, это сильно не скажется на производительности, хотя в другом случае этот же код просто будет разбросан по всем метдам syntax_tree_visitor-а. base_function_call bfc = ret_semantic as base_function_call; if (bfc != null) { if (bfc.simple_function_node.compile_time_executor != null) { expression_node ex = bfc.simple_function_node.compile_time_executor(bfc.location, bfc.parameters.ToArray()); if (ex != null) { return ex; } } } return ret_semantic as expression_node; }
private TextSpan GetSpanIn(SyntaxTree syntaxTree, string textToFind) { string s = syntaxTree.GetText().ToString(); int index = s.IndexOf(textToFind); Assert.True(index >= 0, "textToFind not found in the tree"); return new TextSpan(index, textToFind.Length); }
public void setSource(string source) { this.source = source; this.tree = ASTUtil.GetSyntaxTreeFromSource(source); methods = ASTUtil.GetAllMethodDeclarations(tree); blocks = new List<string>(); methodNames = new List<string>(); foreach (MethodDeclarationSyntax method in methods) { SyntaxNode block = ASTUtil.GetBlockOfMethod(method); if(block != null) { StringBuilder sb = new StringBuilder(); IEnumerable<SyntaxNode> stats = ASTUtil.GetStatementsInNode(block); foreach(StatementSyntax st in stats) { sb.AppendLine(st.GetText()); } blocks.Add(sb.ToString()); } else { blocks.Add(""); } methodNames.Add(method.Identifier.GetText()); } }
public static StringSplitter Create( Document document, int position, SyntaxTree syntaxTree, SyntaxNode root, SourceText sourceText, bool useTabs, int tabSize, CancellationToken cancellationToken) { var token = root.FindToken(position); if (token.IsKind(SyntaxKind.StringLiteralToken)) { return new SimpleStringSplitter( document, position, syntaxTree, root, sourceText, token, useTabs, tabSize, cancellationToken); } var interpolatedStringExpression = TryGetInterpolatedStringExpression(token, position); if (interpolatedStringExpression != null) { return new InterpolatedStringSplitter( document, position, syntaxTree, root, sourceText, interpolatedStringExpression, useTabs, tabSize, cancellationToken); } return null; }
public static ResolveResult Resolve(Lazy<ICompilation> compilation, CSharpUnresolvedFile unresolvedFile, SyntaxTree syntaxTree, TextLocation location, out AstNode node, CancellationToken cancellationToken = default(CancellationToken)) { node = syntaxTree.GetNodeAt(location); if (node == null || node is ArrayInitializerExpression) return null; if (node.Parent is UsingAliasDeclaration && node.Role == UsingAliasDeclaration.AliasRole) { var r = new CSharpAstResolver(compilation.Value, syntaxTree, unresolvedFile); return r.Resolve(((UsingAliasDeclaration)node.Parent).Import, cancellationToken); } if (CSharpAstResolver.IsUnresolvableNode(node)) { if (node is Identifier) { node = node.Parent; } else if (node.NodeType == NodeType.Token) { if (node.Parent is IndexerExpression || node.Parent is ConstructorInitializer) { // There's no other place where one could hover to see the indexer's tooltip, // so we need to resolve it when hovering over the '[' or ']'. // For constructor initializer, the same applies to the 'base'/'this' token. node = node.Parent; } else { return null; } } else { // don't resolve arbitrary nodes - we don't want to show tooltips for everything return null; } } else { // It's a resolvable node. // However, we usually don't want to show the tooltip everywhere // For example, hovering with the mouse over an empty line between two methods causes // node==TypeDeclaration, but we don't want to show any tooltip. if (!node.GetChildByRole(Roles.Identifier).IsNull) { // We'll suppress the tooltip for resolvable nodes if there is an identifier that // could be hovered over instead: return null; } } if (node == null) return null; if (node.Parent is ObjectCreateExpression && node.Role == Roles.Type) { node = node.Parent; } InvocationExpression parentInvocation = null; if ((node is IdentifierExpression || node is MemberReferenceExpression || node is PointerReferenceExpression) && node.Role != Roles.Argument) { // we also need to resolve the invocation parentInvocation = node.Parent as InvocationExpression; } // TODO: I think we should provide an overload so that an existing CSharpAstResolver can be reused CSharpAstResolver resolver = new CSharpAstResolver(compilation.Value, syntaxTree, unresolvedFile); ResolveResult rr = resolver.Resolve(node, cancellationToken); if (rr is MethodGroupResolveResult && parentInvocation != null) return resolver.Resolve(parentInvocation); else return rr; }
private static bool BeginsWithAutoGeneratedComment(SyntaxTree tree, Func<SyntaxTrivia, bool> isComment, CancellationToken cancellationToken) { var root = tree.GetRoot(cancellationToken); if (root.HasLeadingTrivia) { var leadingTrivia = root.GetLeadingTrivia(); foreach (var trivia in leadingTrivia) { if (!isComment(trivia)) { continue; } var text = trivia.ToString(); // Check to see if the text of the comment contains an auto generated comment. foreach (var autoGenerated in s_autoGeneratedStrings) { if (text.Contains(autoGenerated)) { return true; } } } } return false; }
public static Assembly Compile(SyntaxTree tree, string dllName) { var myRefs = new[] { "System", "System.Core", "mscorlib", "System.Runtime" }.Select(MetadataReference.CreateAssemblyReference); var obsRef = new MetadataFileReference(typeof(Observable).Assembly.Location); var synRef = new MetadataFileReference(typeof(CommonSyntaxTree).Assembly.Location); var comRef = new MetadataFileReference(typeof(CompilationOptions).Assembly.Location); myRefs = myRefs.Union(new[] { obsRef, synRef, comRef }); var compiledCode = Compilation.Create( outputName: dllName, options: new CompilationOptions(OutputKind.DynamicallyLinkedLibrary), syntaxTrees: new[] { tree }, references: myRefs); using (var stream = new MemoryStream()) { var emitResult = compiledCode.Emit(stream); if (!emitResult.Success) { var message = string.Join("\r\n", emitResult.Diagnostics); throw new ApplicationException(message); } return Assembly.Load(stream.GetBuffer()); } }
public AbstractIndenter( ISyntaxFactsService syntaxFacts, SyntaxTree syntaxTree, IEnumerable<IFormattingRule> rules, OptionSet optionSet, TextLine lineToBeIndented, CancellationToken cancellationToken) { var syntaxRoot = syntaxTree.GetRoot(cancellationToken); this._syntaxFacts = syntaxFacts; this.OptionSet = optionSet; this.Tree = syntaxTree; this.LineToBeIndented = lineToBeIndented; this.TabSize = this.OptionSet.GetOption(FormattingOptions.TabSize, syntaxRoot.Language); this.CancellationToken = cancellationToken; this.Rules = rules; this.Finder = new BottomUpBaseIndentationFinder( new ChainedFormattingRules(this.Rules, OptionSet), this.TabSize, this.OptionSet.GetOption(FormattingOptions.IndentationSize, syntaxRoot.Language), tokenStream: null, lastToken: default(SyntaxToken)); }
void Init(string code) { syntaxTree = SyntaxTree.Parse(code, "test.cs"); unresolvedFile = syntaxTree.ToTypeSystem(); compilation = TypeSystemHelper.CreateCompilation(unresolvedFile); findReferences = new FindReferences(); }
protected override void CheckResult(bool validLocation, int position, SyntaxTree syntaxTree) { var leftToken = syntaxTree.FindTokenOnLeftOfPosition(position, CancellationToken.None); var isPossibleTupleContext = syntaxTree.IsPossibleTupleContext(leftToken, position); Assert.Equal(validLocation, isPossibleTupleContext); }
public override void visit(SyntaxTree.var_statement defs) { indef = true; ProcessNode(defs.var_def.vars); // исключаем типы - // просматриваем только имена переменных indef = false; }
/// <summary> /// Traverses the symbol table processing XML documentation comments and optionally writing them to /// a provided stream. /// </summary> /// <param name="compilation">Compilation that owns the symbol table.</param> /// <param name="assemblyName">Assembly name override, if specified. Otherwise the <see cref="ISymbol.Name"/> of the source assembly is used.</param> /// <param name="xmlDocStream">Stream to which XML will be written, if specified.</param> /// <param name="diagnostics">Will be supplemented with documentation comment diagnostics.</param> /// <param name="cancellationToken">To stop traversing the symbol table early.</param> /// <param name="filterTree">Only report diagnostics from this syntax tree, if non-null.</param> /// <param name="filterSpanWithinTree">If <paramref name="filterTree"/> and filterSpanWithinTree is non-null, report diagnostics within this span in the <paramref name="filterTree"/>.</param> public static void WriteDocumentationCommentXml(CSharpCompilation compilation, string assemblyName, Stream xmlDocStream, DiagnosticBag diagnostics, CancellationToken cancellationToken, SyntaxTree filterTree = null, TextSpan? filterSpanWithinTree = null) { StreamWriter writer = null; if (xmlDocStream != null && xmlDocStream.CanWrite) { writer = new StreamWriter( stream: xmlDocStream, encoding: new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: false), bufferSize: 0x400, // Default. leaveOpen: true); // Don't close caller's stream. } using (writer) { var compiler = new DocumentationCommentCompiler(assemblyName ?? compilation.SourceAssembly.Name, compilation, writer, filterTree, filterSpanWithinTree, processIncludes: true, isForSingleSymbol: false, diagnostics: diagnostics, cancellationToken: cancellationToken); compiler.Visit(compilation.SourceAssembly.GlobalNamespace); Debug.Assert(compiler._indentDepth == 0); } if (filterTree != null) { // Will respect the DocumentationMode. UnprocessedDocumentationCommentFinder.ReportUnprocessed(filterTree, filterSpanWithinTree, diagnostics, cancellationToken); } else { foreach (SyntaxTree tree in compilation.SyntaxTrees) { // Will respect the DocumentationMode. UnprocessedDocumentationCommentFinder.ReportUnprocessed(tree, null, diagnostics, cancellationToken); } } }
// This constructor can be used to have the span and associated node be arbitrarily different. public SourceLocationWithAssociatedNode(SyntaxTree syntaxTree, TextSpan span, SyntaxNode associatedNode, bool associateInParent) : base(syntaxTree, span) { Debug.Assert(associatedNode != null); //if it's null, construct a SourceLocation instead this.associatedNode = new WeakReference<SyntaxNode>(associatedNode); this.associateInParent = associateInParent; }
public PathSyntaxReference(SyntaxNode node) { this.tree = node.SyntaxTree; this.kind = node.CSharpKind(); this.textSpan = node.Span; this.pathFromRoot = ComputePathFromRoot(node); }
protected static SyntaxNode RecoverNode(SyntaxTree tree, TextSpan textSpan, int kind) { var token = tree.GetRoot().FindToken(textSpan.Start, findInsideTrivia: true); var node = token.Parent; while (node != null) { if (node.Span == textSpan && node.RawKind == kind) { return node; } var structuredTrivia = node as IStructuredTriviaSyntax; if (structuredTrivia != null) { node = structuredTrivia.ParentTrivia.Token.Parent; } else { node = node.Parent; } } throw Contract.Unreachable; }
public bool RemoveCachedSemanticModel(SyntaxTree tree) { lock (_semanticModelsMap) { return _semanticModelsMap.Remove(tree); } }
private void AssertMappedSpanEqual( SyntaxTree syntaxTree, string sourceText, string expectedPath, int expectedStartLine, int expectedStartOffset, int expectedEndLine, int expectedEndOffset, bool hasMappedPath) { var span = GetSpanIn(syntaxTree, sourceText); var mappedSpan = syntaxTree.GetMappedLineSpan(span); var actualDisplayPath = syntaxTree.GetDisplayPath(span, s_resolver); Assert.Equal(hasMappedPath, mappedSpan.HasMappedPath); Assert.Equal(expectedPath, mappedSpan.Path); if (expectedPath == "") { Assert.Equal("", actualDisplayPath); } else { Assert.Equal(string.Format("[{0};{1}]", expectedPath, hasMappedPath ? syntaxTree.FilePath : null), actualDisplayPath); } Assert.Equal(expectedStartLine, mappedSpan.StartLinePosition.Line); Assert.Equal(expectedStartOffset, mappedSpan.StartLinePosition.Character); Assert.Equal(expectedEndLine, mappedSpan.EndLinePosition.Line); Assert.Equal(expectedEndOffset, mappedSpan.EndLinePosition.Character); }
public ToolTipData (ICSharpCode.NRefactory.CSharp.SyntaxTree unit, ICSharpCode.NRefactory.Semantics.ResolveResult result, ICSharpCode.NRefactory.CSharp.AstNode node, CSharpAstResolver file) { this.Unit = unit; this.Result = result; this.Node = node; this.Resolver = file; }
public PositionalSyntaxReference(SyntaxNode node) { this.tree = node.SyntaxTree; this.textSpan = node.Span; this.kind = node.CSharpKind(); System.Diagnostics.Debug.Assert(textSpan.Length > 0); }
private static void VerifyWholeLineIsInactive(SyntaxTree tree, int lineNumber) { var line = tree.GetText().Lines[lineNumber]; for (int pos = line.Start; pos < line.EndIncludingLineBreak; pos++) { Assert.True(tree.IsInInactiveRegion(pos, CancellationToken.None)); } }
public GatherVisitor (BaseRefactoringContext context, SyntaxTree unit, AccessToClosureIssue issueProvider) : base (context) { this.title = context.TranslateString (issueProvider.Title); this.unit = unit; this.issueProvider = issueProvider; }
public CallGraphTest() { source = FileUtil.ReadAllText(path); tree = ASTUtil.GetSyntaxTreeFromSource(source); classDeclaration = tree.GetRoot().DescendantNodes().OfType<ClassDeclarationSyntax>(). First(c => c.Identifier.Value.Equals("CallGraphTest")); graph = new CallGraphBuilder(classDeclaration, tree).BuildCallGraph(); }
private void VerifyNotEquivalent(SyntaxTree tree1, SyntaxTree tree2, bool topLevel) { Assert.False(SyntaxFactory.AreEquivalent(tree1, tree2, topLevel)); // now try as if the second tree were created from scratch. var tree3 = SyntaxFactory.ParseSyntaxTree(tree2.GetText().ToString()); Assert.False(SyntaxFactory.AreEquivalent(tree1, tree3, topLevel)); }
private void InitResolver(SyntaxTree syntaxTree) { if(this.lastFileName != syntaxTree.FileName) { this.lastFileName = syntaxTree.FileName; var unresolvedFile = syntaxTree.ToTypeSystem(); this.resolver = new CSharpAstResolver(compilation, syntaxTree, unresolvedFile); } }
public static void ReportUnprocessed(SyntaxTree tree, TextSpan? filterSpanWithinTree, DiagnosticBag diagnostics, CancellationToken cancellationToken) { if (tree.ReportDocumentationCommentDiagnostics()) { UnprocessedDocumentationCommentFinder finder = new UnprocessedDocumentationCommentFinder(diagnostics, filterSpanWithinTree, cancellationToken); finder.Visit(tree.GetRoot()); } }
private static bool TryGetLoadedSyntaxTree(ImmutableDictionary <string, SyntaxTree> loadedSyntaxTreeMap, DeclarationLoadDirective directive, out SyntaxTree loadedTree) { if (loadedSyntaxTreeMap.TryGetValue(directive.ResolvedPath, out loadedTree)) { return(true); } // If we don't have a tree for this directive, there should be errors. Debug.Assert(directive.Diagnostics.HasAnyErrors()); return(false); }
/// <summary> /// Gets exact location of an error. /// </summary> /// <param name="syntaxTree">Syntax tree.</param> /// <param name="location">Location.</param> /// <param name="position">Position.</param> /// <param name="offset">Offset.</param> /// <returns>Exact location.</returns> private static Location GetLocation(SyntaxTree syntaxTree, Location location, Position position, int offset = 0) { return(Location.Create(syntaxTree, new TextSpan(location.SourceSpan.Start + position.Start + offset, position.Len))); }
protected abstract SyntaxToken GetTokenToLeft(SyntaxTree syntaxTree, int position, CancellationToken cancellationToken);
internal static FunctionDefinition CreateMethod(DestructorDeclarationSyntax node, ISyntaxEntity parent, CodeFile currentCodeFile, SyntaxTree tree) { FunctionDefinition func = createFunctionObject(node.Identifier.Text, tree.GetLineSpan(node.Span), node.Modifiers, parent, currentCodeFile); func.TypeOfFunction = FunctionTypes.Destructor; func.AssociatedComment = GetComment(func, node, tree, currentCodeFile); return(func); }
protected override SyntaxToken GetTokenToRight( SyntaxTree syntaxTree, int position, CancellationToken cancellationToken) { if (position >= syntaxTree.GetText(cancellationToken).Length) { return(default);
private static void AppendAllLoadedSyntaxTrees( ArrayBuilder <SyntaxTree> treesBuilder, SyntaxTree tree, string scriptClassName, SourceReferenceResolver resolver, CommonMessageProvider messageProvider, bool isSubmission, IDictionary <SyntaxTree, int> ordinalMapBuilder, IDictionary <SyntaxTree, ImmutableArray <DeclarationLoadDirective> > loadDirectiveMapBuilder, IDictionary <string, SyntaxTree> loadedSyntaxTreeMapBuilder, IDictionary <SyntaxTree, Lazy <RootSingleNamespaceDeclaration> > declMapBuilder, ref DeclarationTable declTable) { ArrayBuilder <DeclarationLoadDirective> loadDirectives = null; foreach (var directive in tree.GetCompilationUnitRoot().GetLoadDirectives()) { var fileToken = directive.File; var path = (string)fileToken.Value; if (path == null) { // If there is no path, the parser should have some Diagnostics to report (if we're in an active region). Debug.Assert(!directive.IsActive || tree.GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error)); continue; } var diagnostics = DiagnosticBag.GetInstance(); string resolvedFilePath = null; if (resolver == null) { diagnostics.Add( messageProvider.CreateDiagnostic( (int)ErrorCode.ERR_SourceFileReferencesNotSupported, directive.Location)); } else { resolvedFilePath = resolver.ResolveReference(path, baseFilePath: tree.FilePath); if (resolvedFilePath == null) { diagnostics.Add( messageProvider.CreateDiagnostic( (int)ErrorCode.ERR_NoSourceFile, fileToken.GetLocation(), path, CSharpResources.CouldNotFindFile)); } else if (!loadedSyntaxTreeMapBuilder.ContainsKey(resolvedFilePath)) { try { var code = resolver.ReadText(resolvedFilePath); var loadedTree = SyntaxFactory.ParseSyntaxTree( code, tree.Options, // Use ParseOptions propagated from "external" tree. resolvedFilePath); // All #load'ed trees should have unique path information. loadedSyntaxTreeMapBuilder.Add(loadedTree.FilePath, loadedTree); AppendAllSyntaxTrees( treesBuilder, loadedTree, scriptClassName, resolver, messageProvider, isSubmission, ordinalMapBuilder, loadDirectiveMapBuilder, loadedSyntaxTreeMapBuilder, declMapBuilder, ref declTable); } catch (Exception e) { diagnostics.Add( CommonCompiler.ToFileReadDiagnostics(messageProvider, e, resolvedFilePath), fileToken.GetLocation()); } } else { // The path resolved, but we've seen this file before, // so don't attempt to load it again. Debug.Assert(diagnostics.IsEmptyWithoutResolution); } } if (loadDirectives == null) { loadDirectives = ArrayBuilder <DeclarationLoadDirective> .GetInstance(); } loadDirectives.Add(new DeclarationLoadDirective(resolvedFilePath, diagnostics.ToReadOnlyAndFree())); } if (loadDirectives != null) { loadDirectiveMapBuilder.Add(tree, loadDirectives.ToImmutableAndFree()); } }
private DeclarationTreeBuilder(SyntaxTree syntaxTree, string scriptClassName, bool isSubmission) { _syntaxTree = syntaxTree; _scriptClassName = scriptClassName; _isSubmission = isSubmission; }
public Compilation CreateCompilationFromTree(SyntaxTree tree, IEnumerable <MetadataReference> references) { return(CreateCSharpCompilation(references).AddSyntaxTrees(tree)); }
internal static CatchBlock CreateCatchBlock(CatchClauseSyntax node, ISyntaxEntity parent, CodeFile codeFile, SyntaxTree tree) { return(new CatchBlock("", new FileSpan(tree.GetLineSpan(node.Span)), parent, codeFile) { CatchType = node.Declaration.Type.ToString(), CatchFilterClause = (null == node.Filter) ? string.Empty : node.Filter.FilterExpression.ToString() }); }
internal static CSharpCompilation WithSource(this CSharpCompilation compilation, SyntaxTree newTree) { return(compilation.RemoveAllSyntaxTrees().AddSyntaxTrees(newTree)); }
/// <summary> /// This method compiles Service code and retuns ready-to-use assembly /// </summary> /// <param name="Source">Source code to compile</param> /// <param name="TypeToWrap">Type to be wrapped</param> /// <returns></returns> public static Assembly CompileRestServiceSources(string Source, Type TypeToWrap) { #if DEBUG //Write generated code to file var home = AppDomain.CurrentDomain.BaseDirectory; if (!Directory.Exists(home + "\\src")) { Directory.CreateDirectory(home + "\\src"); } File.WriteAllText(home + "src\\" + TypeToWrap.Name + "Source.cs", Source); #endif SyntaxTree ServiceSyntaxTree = CSharpSyntaxTree.ParseText(Source); //References to include in our new assembly List <MetadataReference> references = new List <MetadataReference>(); references.Add(MetadataReference.CreateFromFile(Assembly.Load("netstandard").Location)); references.Add(MetadataReference.CreateFromFile(Assembly.Load("System.Core").Location)); references.Add(MetadataReference.CreateFromFile(typeof(System.Linq.Enumerable).Assembly.Location)); references.Add(MetadataReference.CreateFromFile(typeof(Newtonsoft.Json.JsonConvert).Assembly.Location)); references.Add(MetadataReference.CreateFromFile(Assembly.Load("System.Runtime").Location)); references.Add(MetadataReference.CreateFromFile(Assembly.Load("System.Threading.Tasks").Location)); references.Add(MetadataReference.CreateFromFile(Assembly.Load("System.Collections").Location)); references.Add(MetadataReference.CreateFromFile(typeof(string).GetTypeInfo().Assembly.Location)); //Adds reference to our original class from which we create service references.Add(MetadataReference.CreateFromFile(TypeToWrap.Assembly.Location)); foreach (var reference in TypeToWrap.Assembly.GetReferencedAssemblies()) { var referencedAsm = AppDomain.CurrentDomain.GetAssemblies().SingleOrDefault(assembly => assembly.GetName().Name == reference.Name); if (referencedAsm != null && references.FirstOrDefault(x => x.Display == referencedAsm.Location) == null) { references.Add(MetadataReference.CreateFromFile(referencedAsm.Location)); } } //Prepare to compile CSharpCompilation compilation = CSharpCompilation.Create( TypeToWrap + "Service", //Assembly Name syntaxTrees: new[] { ServiceSyntaxTree }, //Sources to include references: references, options: new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)); //Stream will contain binary IL code using (var ms = new MemoryStream()) { EmitResult compiled = compilation.Emit(ms); //This is where compilation happens if (!compiled.Success) { //Comile error IEnumerable <Diagnostic> failures = compiled.Diagnostics.Where(diagnostic => diagnostic.Severity == DiagnosticSeverity.Error); StringBuilder sb = new StringBuilder(); sb.Append("Failed to compile service code:\r\n"); foreach (Diagnostic diagnostic in failures) { sb.Append(diagnostic.Location + ":" + diagnostic.GetMessage()); sb.Append("\r\n"); } throw new Exception(sb.ToString());//Bad case } else { //Compile success ms.Seek(0, SeekOrigin.Begin); //Reset stream position to beginnig Assembly assembly = AssemblyLoadContext.Default.LoadFromStream(ms); //Load new assembly to memory return(assembly); } } }
public abstract void Visit(SyntaxTree st);
internal static bool IsLoadedSyntaxTree(SyntaxTree tree, ImmutableDictionary <string, SyntaxTree> loadedSyntaxTreeMap) { SyntaxTree loadedTree; return(loadedSyntaxTreeMap.TryGetValue(tree.FilePath, out loadedTree) && (tree == loadedTree)); }
public static SyntaxTree WithInsertAt(this SyntaxTree syntaxTree, int offset, string newText) { return WithReplace(syntaxTree, offset, 0, newText); }
public SyntaxAndDeclarationManager ReplaceSyntaxTree(SyntaxTree oldTree, SyntaxTree newTree) { var state = _lazyState; var newExternalSyntaxTrees = this.ExternalSyntaxTrees.Replace(oldTree, newTree); if (state == null) { return(this.WithExternalSyntaxTrees(newExternalSyntaxTrees)); } var newLoadDirectivesSyntax = newTree.GetCompilationUnitRoot().GetLoadDirectives(); var loadDirectivesHaveChanged = !oldTree.GetCompilationUnitRoot().GetLoadDirectives().SequenceEqual(newLoadDirectivesSyntax); var syntaxTrees = state.SyntaxTrees; var ordinalMap = state.OrdinalMap; var loadDirectiveMap = state.LoadDirectiveMap; var loadedSyntaxTreeMap = state.LoadedSyntaxTreeMap; var removeSet = PooledHashSet <SyntaxTree> .GetInstance(); int totalReferencedTreeCount; ImmutableArray <DeclarationLoadDirective> oldLoadDirectives; GetRemoveSet( oldTree, loadDirectivesHaveChanged, syntaxTrees, ordinalMap, loadDirectiveMap, loadedSyntaxTreeMap, removeSet, out totalReferencedTreeCount, out oldLoadDirectives); var loadDirectiveMapBuilder = loadDirectiveMap.ToBuilder(); var loadedSyntaxTreeMapBuilder = loadedSyntaxTreeMap.ToBuilder(); var declMapBuilder = state.RootNamespaces.ToBuilder(); var declTable = state.DeclarationTable; foreach (var tree in removeSet) { loadDirectiveMapBuilder.Remove(tree); loadedSyntaxTreeMapBuilder.Remove(tree.FilePath); RemoveSyntaxTreeFromDeclarationMapAndTable(tree, declMapBuilder, ref declTable); } removeSet.Free(); var oldOrdinal = ordinalMap[oldTree]; ImmutableArray <SyntaxTree> newTrees; if (loadDirectivesHaveChanged) { // Should have been removed above... Debug.Assert(!loadDirectiveMapBuilder.ContainsKey(oldTree)); Debug.Assert(!loadDirectiveMapBuilder.ContainsKey(newTree)); // If we're inserting new #load'ed trees, we'll rebuild // the whole syntaxTree array and the ordinalMap. var treesBuilder = ArrayBuilder <SyntaxTree> .GetInstance(); var ordinalMapBuilder = PooledDictionary <SyntaxTree, int> .GetInstance(); for (var i = 0; i <= (oldOrdinal - totalReferencedTreeCount); i++) { var tree = syntaxTrees[i]; treesBuilder.Add(tree); ordinalMapBuilder.Add(tree, i); } AppendAllSyntaxTrees( treesBuilder, newTree, this.ScriptClassName, this.Resolver, this.MessageProvider, this.IsSubmission, ordinalMapBuilder, loadDirectiveMapBuilder, loadedSyntaxTreeMapBuilder, declMapBuilder, ref declTable); for (var i = oldOrdinal + 1; i < syntaxTrees.Length; i++) { var tree = syntaxTrees[i]; if (!IsLoadedSyntaxTree(tree, loadedSyntaxTreeMap)) { UpdateSyntaxTreesAndOrdinalMapOnly( treesBuilder, tree, ordinalMapBuilder, loadDirectiveMap, loadedSyntaxTreeMap); } } newTrees = treesBuilder.ToImmutableAndFree(); ordinalMap = ordinalMapBuilder.ToImmutableDictionaryAndFree(); Debug.Assert(newTrees.Length == ordinalMap.Count); } else { AddSyntaxTreeToDeclarationMapAndTable(newTree, this.ScriptClassName, this.IsSubmission, declMapBuilder, ref declTable); if (newLoadDirectivesSyntax.Any()) { // If load directives have not changed and there are new directives, // then there should have been (matching) old directives as well. Debug.Assert(!oldLoadDirectives.IsDefault); Debug.Assert(!oldLoadDirectives.IsEmpty); Debug.Assert(oldLoadDirectives.Length == newLoadDirectivesSyntax.Count); loadDirectiveMapBuilder[newTree] = oldLoadDirectives; } Debug.Assert(ordinalMap.ContainsKey(oldTree)); // Checked by RemoveSyntaxTreeFromDeclarationMapAndTable newTrees = syntaxTrees.SetItem(oldOrdinal, newTree); ordinalMap = ordinalMap.Remove(oldTree); ordinalMap = ordinalMap.SetItem(newTree, oldOrdinal); } state = new State( newTrees, ordinalMap, loadDirectiveMapBuilder.ToImmutable(), loadedSyntaxTreeMapBuilder.ToImmutable(), declMapBuilder.ToImmutable(), declTable); return(new SyntaxAndDeclarationManager( newExternalSyntaxTrees, this.ScriptClassName, this.Resolver, this.MessageProvider, this.IsSubmission, state)); }
public static SyntaxTree WithInsertBefore(this SyntaxTree syntaxTree, string existingText, string newText) { var oldFullText = syntaxTree.GetText().ToString(); int offset = oldFullText.IndexOf(existingText); return WithReplace(syntaxTree, offset, 0, newText); }
protected override MemberDeclarationSyntax?GetContainingMember(SyntaxTree syntaxTree, int position, CancellationToken cancellationToken) { return(syntaxTree.GetRoot(cancellationToken).FindToken(position).GetAncestor <MemberDeclarationSyntax>()); }
internal static Comment GetComment(ISyntaxEntity owner, CSharpSyntaxNode node, SyntaxTree tree, CodeFile currentCodeFile) { var trivias = node.GetLeadingTrivia().Where(t => t.Kind() == SyntaxKind.MultiLineDocumentationCommentTrivia || t.Kind() == SyntaxKind.MultiLineCommentTrivia || t.Kind() == SyntaxKind.SingleLineDocumentationCommentTrivia || t.Kind() == SyntaxKind.SingleLineCommentTrivia); if (trivias.Any()) { string commentText = String.Empty; FileSpan overallSpan = null; foreach (var trivia in trivias) { if (trivia != null && trivia.Token.Value != null) { overallSpan = processSpan(overallSpan, tree.GetLineSpan(trivia.Span)); if (trivia.Kind() == SyntaxKind.MultiLineDocumentationCommentTrivia || trivia.Kind() == SyntaxKind.SingleLineDocumentationCommentTrivia) { var xml = trivia.GetStructure(); commentText += String.Join(Environment.NewLine, xml.GetText().Lines); } else { commentText += trivia.ToFullString(); } } } var comment = new Comment(commentText, overallSpan, owner, currentCodeFile); comment.Parent = owner; currentCodeFile.AddComment(comment); return(comment); } else { return(null); } }
internal static FunctionDefinition CreateMethod(LambdaExpressionSyntax node, ISyntaxEntity parent, CodeFile currentCodeFile, SyntaxTree tree) { FunctionDefinition func = createFunctionObject("", tree.GetLineSpan(node.Span), new SyntaxTokenList(), parent, currentCodeFile); func.TypeOfFunction = FunctionTypes.AnonymousFunction; func.AssociatedComment = GetComment(func, node, tree, currentCodeFile); return(func); }
internal static ElseBlock CreateElseBlock(ElseClauseSyntax node, ISyntaxEntity parent, CodeFile codeFile, SyntaxTree tree) { return(new ElseBlock("", new FileSpan(tree.GetLineSpan(node.Span)), parent, codeFile)); }
internal static UserDefinedType CreateInterface(BaseTypeDeclarationSyntax node, ISyntaxEntity parent, CodeFile currentCodeFile, SyntaxTree tree) { UserDefinedType typeObj = new InterfaceDefinition(node.Identifier.Text, new FileSpan(tree.GetLineSpan(node.Span)), parent, currentCodeFile); processModifiers(typeObj, node.Modifiers); typeObj.AccessSpecifiers = typeObj.AccessSpecifiers == AccessSpecifiers.None ? AccessSpecifiers.Internal : typeObj.AccessSpecifiers; typeObj.AssociatedComment = GetComment(typeObj, node, tree, currentCodeFile); return(typeObj); }
protected abstract TMemberNode?GetContainingMember(SyntaxTree syntaxTree, int position, CancellationToken cancellationToken);
internal static WhileBlock CreateWhileBlock(WhileStatementSyntax node, ISyntaxEntity parent, CodeFile codeFile, SyntaxTree tree) { return(new WhileBlock("", new FileSpan(tree.GetLineSpan(node.Span)), parent, codeFile)); }
public bool Visit(SyntaxTree node) => VisitChildren(node);
protected abstract bool SupportsDiscard(SyntaxTree tree);
internal static bool ReportDocumentationCommentDiagnostics(this SyntaxTree tree) { return(tree.Options.DocumentationMode >= DocumentationMode.Diagnose); }
/// <summary> /// Get options for a given <paramref name="tree"/>. /// </summary> public abstract AnalyzerConfigOptions GetOptions(SyntaxTree tree);
internal static TryBlock CreateTryBlock(TryStatementSyntax node, ISyntaxEntity parent, CodeFile codeFile, SyntaxTree tree) { var tryBlock = new TryBlock("", new FileSpan(tree.GetLineSpan(node.Span)), parent, codeFile); return(tryBlock); }
public SyntaxReferenceLocation(SyntaxNode node, SyntaxTree tree) : this(tree.GetReference(node)) { }
protected override void DoEmit() { this.Emitter.Writers = new Stack <IWriter>(); this.Emitter.Outputs = new EmitterOutputs(); var metas = new Dictionary <IType, JObject>(); this.Emitter.Translator.Plugins.BeforeTypesEmit(this.Emitter, this.Emitter.Types); this.Emitter.ReflectableTypes = this.GetReflectableTypes(); var reflectedTypes = this.Emitter.ReflectableTypes; var tmpBuffer = new StringBuilder(); StringBuilder currentOutput = null; foreach (var type in this.Emitter.Types) { this.Emitter.Translator.Plugins.BeforeTypeEmit(this.Emitter, type); this.Emitter.Translator.EmitNode = type.TypeDeclaration; var typeDef = type.Type.GetDefinition(); bool isNative; if (this.Emitter.Validator.IsExternalInterface(typeDef, out isNative)) { this.Emitter.Translator.Plugins.AfterTypeEmit(this.Emitter, type); continue; } if (type.IsObjectLiteral) { var mode = this.Emitter.Validator.GetObjectCreateMode(this.Emitter.GetTypeDefinition(type.Type)); var ignore = mode == 0 && !type.Type.GetMethods(null, GetMemberOptions.IgnoreInheritedMembers).Any(m => !m.IsConstructor && !m.IsAccessor); if (this.Emitter.Validator.IsIgnoreType(typeDef) || ignore) { this.Emitter.Translator.Plugins.AfterTypeEmit(this.Emitter, type); continue; } } this.Emitter.InitEmitter(); ITypeInfo typeInfo; if (this.Emitter.TypeInfoDefinitions.ContainsKey(type.Key)) { typeInfo = this.Emitter.TypeInfoDefinitions[type.Key]; type.Module = typeInfo.Module; type.FileName = typeInfo.FileName; type.Dependencies = typeInfo.Dependencies; typeInfo = type; } else { typeInfo = type; } this.Emitter.Output = this.GetOutputForType(typeInfo, null); this.Emitter.TypeInfo = type; if (this.Emitter.Output.Length > 0) { this.WriteNewLine(); } tmpBuffer.Length = 0; currentOutput = this.Emitter.Output; this.Emitter.Output = tmpBuffer; if (this.Emitter.TypeInfo.Module != null) { this.Indent(); } new ClassBlock(this.Emitter, this.Emitter.TypeInfo).Emit(); this.Emitter.Translator.Plugins.AfterTypeEmit(this.Emitter, type); currentOutput.Append(tmpBuffer.ToString()); this.Emitter.Output = currentOutput; } this.Emitter.NamespacesCache = new Dictionary <string, int>(); foreach (var type in this.Emitter.Types) { var typeDef = type.Type.GetDefinition(); bool isGlobal = false; if (typeDef != null) { isGlobal = typeDef.Attributes.Any(a => a.AttributeType.FullName == "Bridge.GlobalMethodsAttribute" || a.AttributeType.FullName == "Bridge.MixinAttribute"); } if (reflectedTypes.Any(t => t == type.Type) || isGlobal) { continue; } var meta = MetadataUtils.ConstructTypeMetadata(typeDef, this.Emitter, true, type.TypeDeclaration.GetParent <SyntaxTree>()); if (meta != null) { metas.Add(type.Type, meta); } } foreach (var reflectedType in reflectedTypes) { var typeDef = reflectedType.GetDefinition(); JObject meta = null; if (typeDef != null) { var tInfo = this.Emitter.Types.FirstOrDefault(t => t.Type == reflectedType); SyntaxTree tree = null; if (tInfo != null && tInfo.TypeDeclaration != null) { tree = tInfo.TypeDeclaration.GetParent <SyntaxTree>(); } meta = MetadataUtils.ConstructTypeMetadata(reflectedType.GetDefinition(), this.Emitter, false, tree); } else { meta = MetadataUtils.ConstructITypeMetadata(reflectedType, this.Emitter); } if (meta != null) { metas.Add(reflectedType, meta); } } var lastOutput = this.Emitter.Output; var output = this.Emitter.AssemblyInfo.Reflection.Output; if (!string.IsNullOrEmpty(output)) { this.Emitter.Output = this.GetOutputForType(null, output); this.Emitter.MetaDataOutputName = this.Emitter.EmitterOutput.FileName; } var scriptableAttributes = MetadataUtils.GetScriptableAttributes(this.Emitter.Resolver.Compilation.MainAssembly.AssemblyAttributes, this.Emitter, null).ToList(); bool hasMeta = metas.Count > 0 || scriptableAttributes.Count > 0; if (hasMeta) { this.WriteNewLine(); int pos = 0; if (metas.Count > 0) { this.Write("var $m = " + JS.Types.Bridge.SET_METADATA + ","); this.WriteNewLine(); this.Write(Bridge.Translator.Emitter.INDENT + "$n = "); pos = this.Emitter.Output.Length; this.Write(";"); this.WriteNewLine(); } foreach (var meta in metas) { var metaData = meta.Value; string typeArgs = ""; if (meta.Key.TypeArguments.Count > 0) { StringBuilder arr_sb = new StringBuilder(); var comma = false; foreach (var typeArgument in meta.Key.TypeArguments) { if (comma) { arr_sb.Append(", "); } arr_sb.Append(typeArgument.Name); comma = true; } typeArgs = arr_sb.ToString(); } this.Write(string.Format("$m({0}, function ({2}) {{ return {1}; }});", MetadataUtils.GetTypeName(meta.Key, this.Emitter, false, true), metaData.ToString(Formatting.None), typeArgs)); this.WriteNewLine(); } if (pos > 0) { this.Emitter.Output.Insert(pos, this.Emitter.ToJavaScript(this.Emitter.NamespacesCache.OrderBy(key => key.Value).Select(item => new JRaw(item.Key)).ToArray())); this.Emitter.NamespacesCache = null; } if (scriptableAttributes.Count > 0) { JArray attrArr = new JArray(); foreach (var a in scriptableAttributes) { attrArr.Add(MetadataUtils.ConstructAttribute(a, null, this.Emitter)); } this.Write(string.Format("$asm.attr= {0};", attrArr.ToString(Formatting.None))); this.WriteNewLine(); } } this.Emitter.Output = lastOutput; //this.RemovePenultimateEmptyLines(true); this.Emitter.Translator.Plugins.AfterTypesEmit(this.Emitter, this.Emitter.Types); }