Exemplo n.º 1
0
        public IChameleonNode ReSync(CachingLexer cachingLexer, TreeTextRange changedRange, int insertedTextLen)
        {
            TreeOffset currStartOffset = GetTreeStartOffset();
            int        currLength      = GetTextLength();

            Logger.Assert(changedRange.StartOffset >= currStartOffset && changedRange.EndOffset <= (currStartOffset + currLength),
                          "changedRange.StartOffset >= currStartOffset && changedRange.EndOffset <= (currStartOffset+currLength)");

            int newLength = currLength - changedRange.Length + insertedTextLen;

            LanguageService languageService = Language.LanguageService();

            if (languageService != null)
            {
                var         parser     = (IPsiParser)languageService.CreateParser(new ProjectedLexer(cachingLexer, new TextRange(currStartOffset.Offset, currStartOffset.Offset + newLength)), GetPsiModule(), GetSourceFile());
                TreeElement newElement = parser.ParseStatement();
                if (newElement.GetTextLength() == 0)
                {
                    return(null);
                }
                if ((newElement.GetTextLength() == newLength) && (";".Equals(newElement.GetText().Substring(newElement.GetTextLength() - 1))))
                {
                    var psiFile = GetContainingNode <PsiFile>();
                    if (psiFile != null)
                    {
                        psiFile.ClearTables();
                    }
                    return(newElement as IRuleDeclaration);
                }
            }
            return(null);
        }
        public override ISpecificCodeCompletionContext GetCompletionContext(CodeCompletionContext context)
        {
            var unterminatedContext = new NTriplesReparsedCompletionContext(context.File, context.SelectedTreeRange, "aaa");

            unterminatedContext.Init();
            IReference referenceToComplete = unterminatedContext.Reference;
            ITreeNode  elementToComplete   = unterminatedContext.TreeNode;

            if (elementToComplete == null)
            {
                return(null);
            }

            TreeTextRange referenceRange = referenceToComplete != null
                                               ? referenceToComplete.GetTreeTextRange()
                                               : GetElementRange(elementToComplete);

            TextRange referenceDocumentRange = unterminatedContext.ToDocumentRange(referenceRange);

            if (!referenceDocumentRange.IsValid)
            {
                return(null);
            }

            if (!referenceDocumentRange.Contains(context.CaretDocumentRange.TextRange))
            {
                return(null);
            }

            TextLookupRanges ranges = GetTextLookupRanges(context, referenceDocumentRange);

            return(new NTriplesCodeCompletionContext(context, ranges, unterminatedContext));
        }
        private static void MakeDocumentChanges(
            ISolution solution,
            List <FileGeneratorOutput> fileGeneratorOutputs,
            List <InPlaceGeneratorOutput> inPlaceGeneratorOutputs)
        {
            foreach (FileGeneratorOutput output in fileGeneratorOutputs)
            {
                IDocument document = output.GeneratedProjectFile.GetDocument();
                document.ReplaceText(document.DocumentRange, output.GeneratedText);
                ExecutionHelpers.OrginizeUsingsAndFormatFile(solution, document);
            }

            foreach (InPlaceGeneratorOutput output in inPlaceGeneratorOutputs)
            {
                IDocument document = output.ProjectFile.GetDocument();
                if (!output.RangeToDelete.IsEmpty)
                {
                    document.DeleteText(output.RangeToDelete);
                }

                document.InsertText(output.PositionToInsert, output.GeneratedText);

                var treeTextRange = TreeTextRange.FromLength(new TreeOffset(output.PositionToInsert), output.GeneratedText.Length);
                ExecutionHelpers.FormatFileRangeAndAddUsingDirectives(solution, document, treeTextRange, output.MissingUsingDirectives);
            }
        }
        /// <summary>
        /// The process of generated document commit (in the case of primary document incremental reparse) can be overridden in this method.
        /// Returns null if full regeneration is required.
        /// This method is not allowed to do destructive changes due to interruptibility!
        /// </summary>
        public override ICollection <IPreCommitResult> ExecuteSecondaryDocumentCommitWork(PrimaryFileModificationInfo primaryFileModificationInfo,
                                                                                          CachedPsiFile cachedPsiFile, TreeTextRange oldTreeRange, string newText)
        {
            var rangeTranslator = (RangeTranslatorWithGeneratedRangeMap)cachedPsiFile.PsiFile.SecondaryRangeTranslator;

            if (rangeTranslator == null)
            {
                return(null);
            }

            TreeTextRange range         = rangeTranslator.OriginalToGenerated(oldTreeRange, JetPredicate <IUserDataHolder> .True);
            DocumentRange documentRange = cachedPsiFile.PsiFile.DocumentRangeTranslator.Translate(range);

            if (!documentRange.IsValid())
            {
                return(null);
            }

            var documentChange = new DocumentChange(documentRange.Document, documentRange.TextRange.StartOffset, documentRange.TextRange.Length, newText,
                                                    documentRange.Document.LastModificationStamp, TextModificationSide.NotSpecified);

            return(new IPreCommitResult[] {
                new PreCommitResult(cachedPsiFile.WorkIncrementalParse(documentChange), null, documentChange, null, TextRange.InvalidRange, string.Empty),
                new FixRangeTranslatorsOnSharedRangeCommitResult(rangeTranslator, null, new TreeTextRange <Original>(oldTreeRange),
                                                                 new TreeTextRange <Generated>(range), newText)
            });
        }
        public IJsonNewLiteralExpression GetTreeNode()
        {
            var range = TreeTextRange.FromLength(new TreeOffset(DeclarationOffset), ShortName.Length);
            var node  = SourceFile.GetPrimaryPsiFile()?.FindNodeAt(range);

            return(node?.Parent as IJsonNewLiteralExpression);
        }
        public DocumentRange Translate(TreeTextRange range)
        {
            if (!range.IsValid() || !SourceFile.IsValid())
            {
                return(DocumentRange.InvalidRange);
            }
            var sector = FindSectorAtRange(range);

            if (!sector.IsValid())
            {
                return(DocumentRange.InvalidRange);
            }

            // Let the included file handle the request
            if (sector.Include != null)
            {
                return(sector.Include.DocumentRangeTranslator.Translate(range));
            }

            // The range is in the current document

            // The includes that appear before do not contribute to document offset
            int extraIncludeOffset = sector.PrecedingIncludeLength;

            // Neither do the other includes in the tree
            // (the ones that are included before the current file)
            int extraRootOffset = FileLikeNode.GetTreeStartOffset().Offset;

            var start = range.StartOffset - extraIncludeOffset - extraRootOffset;
            var end   = range.EndOffset - extraIncludeOffset - extraRootOffset;
            var resultingTextRange = new TextRange(start.Offset, end.Offset);

            resultingTextRange.AssertValid();
            return(new DocumentRange(SourceFile.Document, resultingTextRange));
        }
Exemplo n.º 7
0
        private static DeclaredElementInfo FindDeclaration([NotNull] ITreeNode node, [NotNull] IFile file)
        {
            var declaration = node.GetContainingNode <IDeclaration>(true);

            if (declaration == null)
            {
                return(null);
            }

            TreeTextRange nameRange = declaration.GetNameRange();

            if (!nameRange.Intersects(node.GetTreeTextRange()))
            {
                return(null);
            }

            IDeclaredElement declaredElement = declaration.DeclaredElement;

            if (declaredElement == null)
            {
                return(null);
            }

            return(new DeclaredElementInfo(declaredElement, EmptySubstitution.INSTANCE, file, file.GetDocumentRange(nameRange).TextRange, null));
        }
        public static void FormatFileRangeAndAddUsingDirectives(
            ISolution solution,
            IDocument document,
            TreeTextRange treeTextRange,
            IReadOnlyCollection <IUsingDirective> usingDirectives)
        {
            IPsiSourceFile sourceFile  = document.GetPsiSourceFile(solution);
            IPsiServices   psiServices = solution.GetPsiServices();

            psiServices.Files.CommitAllDocuments();

            PsiTransactionCookie.ExecuteConditionally(
                psiServices,
                () =>
            {
                if (sourceFile?.GetPsiFile(CSharpLanguage.Instance, new DocumentRange(document, 0)) is ICSharpFile psiFile)
                {
                    psiFile.FormatFileRange(treeTextRange);

                    foreach (IUsingDirective usingDirective in usingDirectives)
                    {
                        psiFile.AddImport(usingDirective);
                    }
                }

                return(true);
            },
                "Format T4 Generated File"
                );
        }
        private static void ProcessT4FeatureBlock(
            [NotNull] IT4FeatureBlock featureBlock,
            [NotNull] CodeStructureElement parentElement,
            [NotNull] ICSharpFile cSharpFile,
            [NotNull] ISecondaryRangeTranslator secondaryRangeTranslator,
            [NotNull] CSharpCodeStructureProcessingState state
            )
        {
            TreeTextRange t4Range     = featureBlock.Code.GetTreeTextRange();
            TreeTextRange cSharpRange = secondaryRangeTranslator.OriginalToGenerated(t4Range);

            if (!cSharpRange.IsValid())
            {
                return;
            }

            TreeOffset cSharpStart = cSharpRange.StartOffset;
            TreeOffset cSharpEnd   = cSharpRange.EndOffset;

            ITreeNode containingNode = cSharpFile.FindNodeAt(cSharpRange);

            if (containingNode == null)
            {
                return;
            }

            for (ITreeNode node = containingNode.FirstChild; node != null; node = node.NextSibling)
            {
                TreeOffset nodeStart = node.GetTreeStartOffset();
                if (nodeStart >= cSharpStart && nodeStart < cSharpEnd)
                {
                    ProcessCSharpNode(node, parentElement, state);
                }
            }
        }
Exemplo n.º 10
0
        public DocumentRange Translate(TreeTextRange range)
        {
            if (!range.IsValid())
                return DocumentRange.InvalidRange;
            if (_sourceFile == null || !_sourceFile.IsValid())
                return DocumentRange.InvalidRange;

            IncludeWithOffset atStart = FindIncludeAtOffset(range.StartOffset, true);
            IncludeWithOffset atEnd = FindIncludeAtOffset(range.EndOffset, atStart.Include == null);

            // two different parts are overlapping
            IT4Include include = atStart.Include;
            if (include != atEnd.Include)
                return DocumentRange.InvalidRange;

            // recursive includes
            if (include != null) {
                if (include.DocumentRangeTranslator != null)
                    return include.DocumentRangeTranslator.Translate(range);
                return DocumentRange.InvalidRange;
            }

            int rootStartOffset = _root.GetTreeStartOffset().Offset;
            return new DocumentRange(_sourceFile.Document, new TextRange(atStart.Offset - rootStartOffset, atEnd.Offset - rootStartOffset));
        }
Exemplo n.º 11
0
        private void HighlightDeclarationsInFile(IDeclaredElement declaredElement, IPsiView psiView, HighlightingsConsumer consumer)
        {
            // There are no IDeclarations for this declared element, try and find the associated string literal expression
            var asmdefNameDeclaredElement = declaredElement as AsmDefNameDeclaredElement;

            if (asmdefNameDeclaredElement == null)
            {
                return;
            }

            foreach (var psiSourceFile in psiView.SortedSourceFiles)
            {
                if (psiSourceFile != asmdefNameDeclaredElement.SourceFile)
                {
                    continue;
                }

                var primaryPsiFile = psiSourceFile.GetPrimaryPsiFile();
                var node           = primaryPsiFile?.FindNodeAt(TreeTextRange.FromLength(
                                                                    new TreeOffset(asmdefNameDeclaredElement.DeclarationOffset),
                                                                    asmdefNameDeclaredElement.ShortName.Length));
                var literalExpression = node?.GetContainingNode <IJavaScriptLiteralExpression>();
                if (literalExpression != null)
                {
                    HighlightFoundDeclaration(literalExpression, consumer);
                }
            }
        }
Exemplo n.º 12
0
        public virtual IChameleonNode ReSync(CachingLexer cachingLexer, TreeTextRange changedRange, int insertedTextLen)
        {
            TreeTextRange oldRange = this.GetTreeTextRange();

            Logger.Assert(changedRange.ContainedIn(oldRange), "The condition “changedRange.ContainedIn(oldRange)” is false.");

            int newLength = oldRange.Length - changedRange.Length + insertedTextLen;

            // Find starting comment
            if (!cachingLexer.FindTokenAt(oldRange.StartOffset.Offset) ||
                cachingLexer.TokenType != this.GetTokenType() ||
                cachingLexer.TokenStart != oldRange.StartOffset.Offset ||
                cachingLexer.TokenEnd != oldRange.StartOffset.Offset + newLength)
            {
                return(null);
            }

            var element = TreeElementFactory.CreateLeafElement(
                cachingLexer.TokenType,
                new ProjectedBuffer(
                    cachingLexer.Buffer, new TextRange(cachingLexer.TokenStart, cachingLexer.TokenStart + newLength)),
                0,
                newLength);
            var comment = element as Comment;

            if (comment == null || this.CommentType != comment.CommentType)
            {
                return(null);
            }
            return(comment);
        }
        public IJavaScriptLiteralExpression GetTreeNode()
        {
            var range = TreeTextRange.FromLength(new TreeOffset(DeclarationOffset), ShortName.Length);
            var node  = SourceFile.GetPrimaryPsiFile()?.FindNodeAt(range);

            return(JavaScriptLiteralExpressionNavigator.GetByLiteral(node as ITokenNode));
        }
Exemplo n.º 14
0
        /// <summary>
        /// Determines whether a specified C# using directive can be removed.
        /// </summary>
        /// <param name="document">The document.</param>
        /// <param name="usingDirective">The using directive.</param>
        /// <returns><c>true</c> if the specified using directive can be removed; otherwise, <c>false</c>.</returns>
        /// <remarks>As long as the using is represented as a T4 import directive in the root file, it can be removed.</remarks>
        public bool CanRemoveUsing(IDocument document, IUsingDirective usingDirective)
        {
            TreeTextRange nameRange = GetNameRange(usingDirective);

            if (!nameRange.IsValid())
            {
                return(false);
            }

            IFile containingFile = usingDirective.GetContainingFile();

            if (containingFile == null)
            {
                return(false);
            }

            DocumentRange documentRange = containingFile.GetDocumentRange(nameRange);

            return(documentRange.IsValid() && documentRange.Document == document);

//			IReferenceName namespaceNode = usingDirective.GetUsedNamespaceNode();
//			if (namespaceNode == null)
//				return false;
//
//			var directive = namespaceNode.GetT4ContainerFromCSharpNode<IT4Directive>();
//			return directive != null && directive.GetContainingNode<IT4Include>() == null;
        }
Exemplo n.º 15
0
        public static PropertyContractInfo TryCreate(
            [NotNull] IIndexerDeclaration declaration,
            TreeTextRange selectedTreeRange,
            [NotNull] Func <IType, bool> isAvailableForType)
        {
            if (declaration.GetNameRange().Contains(selectedTreeRange) &&
                declaration.ArrowClause == null &&
                declaration.AccessorDeclarations.Any(accessorDeclaration => accessorDeclaration.AssertNotNull().ArrowClause == null))
            {
                var property = declaration.DeclaredElement;

                Debug.Assert(property != null);

                if (CanAcceptContracts(property) && isAvailableForType(property.Type))
                {
                    var contractKind = property.IsReadable
                        ? (property.IsWritable ? ContractKind.RequiresAndEnsures : ContractKind.Ensures)
                        : (property.IsWritable ? (ContractKind?)ContractKind.Requires : null);
                    if (contractKind != null)
                    {
                        return(new PropertyContractInfo((ContractKind)contractKind, declaration, property.Type));
                    }
                }
            }

            return(null);
        }
Exemplo n.º 16
0
        public DocumentRange Translate(TreeTextRange range)
        {
            if (!range.IsValid() || !_sourceFile.IsValid())
            {
                return(DocumentRange.InvalidRange);
            }

            IncludeWithOffset atStart = FindIncludeAtOffset(range.StartOffset, true);
            IncludeWithOffset atEnd   = FindIncludeAtOffset(range.EndOffset, atStart.Include == null);

            // two different parts are overlapping
            IT4Include include = atStart.Include;

            if (include != atEnd.Include)
            {
                return(DocumentRange.InvalidRange);
            }

            // recursive includes
            if (include != null)
            {
                if (include.DocumentRangeTranslator != null)
                {
                    return(include.DocumentRangeTranslator.Translate(range));
                }
                return(DocumentRange.InvalidRange);
            }

            int rootStartOffset = _root.GetTreeStartOffset().Offset;

            return(new DocumentRange(_sourceFile.Document, new TextRange(atStart.Offset - rootStartOffset, atEnd.Offset - rootStartOffset)));
        }
Exemplo n.º 17
0
        public static IEnumerable <string> GetAplicableKeywords(
            INTriplesFile file, TreeTextRange referenceRange, NTriplesCodeCompletionContext context)
        {
            var list = new List <string>();
            var node = file.FindNodeAt(referenceRange);

            if (node == null)
            {
                return(list);
            }

            var isTopLevel = IsTopLevel(node);
            var kind       = GetKind(node);

            if (isTopLevel && (kind == IdentifierKind.Subject || kind == IdentifierKind.Other))
            {
                list.AddRange(DirectiveKeywords);
                list.AddRange(MetaKeywords);
            }

            if (kind != IdentifierKind.Subject)
            {
                list.AddRange(PredicateKeywords);
                list.Add(OfPredicateKeyword1);
                list.Add(OfPredicateKeyword2);
            }

            list.AddRange(ObjectLiteralKeywords);

            return(list);
        }
        public static PropertyContractInfo TryCreate(
            [NotNull] IPropertyDeclaration declaration, TreeTextRange selectedTreeRange, [NotNull] Func<IType, bool> isAvailableForType)
        {
            if (declaration.GetNameRange().Contains(selectedTreeRange) && declaration.ArrowExpression == null)
            {
                var property = declaration.DeclaredElement;

                Debug.Assert(property != null);

                if (CanAcceptContracts(property) && isAvailableForType(property.Type))
                {
                    var contractKind = declaration.IsAuto
                                           ? (declaration.IsStatic ? (ContractKind?)null : ContractKind.Invariant)
                                           : property.IsReadable
                                                 ? (property.IsWritable ? ContractKind.RequiresAndEnsures : ContractKind.Ensures)
                                                 : (property.IsWritable ? (ContractKind?)ContractKind.Requires : null);
                    if (contractKind != null)
                    {
                        return new PropertyContractInfo((ContractKind)contractKind, declaration, property.Type);
                    }
                }
            }

            return null;
        }
 private GeneratorDataProvider(
     ISolution solution,
     IProject project,
     IPsiModule psiModule,
     IPsiServices psiServices,
     IPsiSourceFile sourceFile,
     ICSharpFile psiFile,
     ITreeNode selectedElement,
     IDocument document,
     TreeTextRange selectedTreeRange,
     DocumentRange documentSelection,
     ITreeNode tokenAfterCaret,
     ITreeNode tokenBeforeCaret,
     CSharpElementFactory elementFactory)
 {
     this.Solution          = solution;
     this.Project           = project;
     this.PsiModule         = psiModule;
     this.PsiServices       = psiServices;
     this.SourceFile        = sourceFile;
     this.PsiFile           = psiFile;
     this.SelectedElement   = selectedElement;
     this.Document          = document;
     this.SelectedTreeRange = selectedTreeRange;
     this.DocumentSelection = documentSelection;
     this.TokenAfterCaret   = tokenAfterCaret;
     this.TokenBeforeCaret  = tokenBeforeCaret;
     this.ElementFactory    = elementFactory;
 }
Exemplo n.º 20
0
        private static DeclaredElementInfo FindDeclaredElement(DocumentRange range, [NotNull] IFile file)
        {
            if (!file.IsValid())
            {
                return(null);
            }

            TreeTextRange treeTextRange = file.Translate(range);

            if (!treeTextRange.IsValid())
            {
                return(null);
            }

            IReference[] references = file.FindReferencesAt(treeTextRange);
            if (references.Length > 0)
            {
                return(GetBestReference(references, file));
            }

            // FindNodeAt seems to return the previous node on single-char literals (eg '0'). FindNodesAt is fine.
            var node = file.FindNodesAt <ITreeNode>(treeTextRange).FirstOrDefault();

            if (node == null || !node.IsValid())
            {
                return(null);
            }

            return(FindDeclaration(node, file)
                   ?? FindConstant(node, file)
                   ?? FindSpecialElement(node, file));
        }
Exemplo n.º 21
0
        public static ContractInfo TryCreate(
            IDeclaration declaration,
            TreeTextRange selectedTreeRange,
            [NotNull] Func <IType, bool> isAvailableForType)
        {
            switch (declaration)
            {
            case IParameterDeclaration parameterDeclaration: return(ParameterContractInfo.TryCreate(parameterDeclaration, isAvailableForType));

            case IMethodDeclaration methodDeclaration:
                return(MethodContractInfo.TryCreate(methodDeclaration, selectedTreeRange, isAvailableForType));

            case IPropertyDeclaration propertyDeclaration:
                return(PropertyContractInfo.TryCreate(propertyDeclaration, selectedTreeRange, isAvailableForType));

            case IIndexerDeclaration indexerDeclaration:
                return(PropertyContractInfo.TryCreate(indexerDeclaration, selectedTreeRange, isAvailableForType));

            case IFieldDeclaration fieldDeclaration: return(FieldContractInfo.TryCreate(fieldDeclaration, isAvailableForType));

            case IOperatorDeclaration operatorDeclaration:
                return(OperatorContractInfo.TryCreate(operatorDeclaration, selectedTreeRange, isAvailableForType));

            default: return(null);
            }
        }
Exemplo n.º 22
0
        private static DeclaredElementInfo FindConstant([NotNull] ITreeNode node, [NotNull] IFile file)
        {
            var literalExpression = node.GetContainingNode <ILiteralExpression>(true);

            if (literalExpression == null)
            {
                return(null);
            }

            TreeTextRange literalRange = literalExpression.Literal.GetTreeTextRange();

            if (!literalRange.Intersects(node.GetTreeTextRange()))
            {
                return(null);
            }

            var declaredType = literalExpression.ConstantValue.Type as IDeclaredType;

            if (declaredType == null)
            {
                return(null);
            }

            ITypeElement typeElement = declaredType.GetTypeElement();

            if (typeElement == null)
            {
                return(null);
            }

            return(new DeclaredElementInfo(typeElement, declaredType.GetSubstitution(), file, file.GetDocumentRange(literalRange).TextRange, null));
        }
Exemplo n.º 23
0
        private static string TryGetIndentFromStatement(
            [NotNull] ISecondaryRangeTranslator rangeTranslator,
            [NotNull] ITreeNode currentNode
            )
        {
            if (!(currentNode is IStatement))
            {
                return(null);
            }
            var token      = currentNode.GetFirstTokenIn();
            var tokenRange = token.GetDocumentRange();

            if (!tokenRange.IsValid())
            {
                return(null);
            }
            if (tokenRange.TextRange.EndOffset >= rangeTranslator.OriginalFile.GetTextLength())
            {
                return(null);
            }
            var generatedTokenRange = new TreeTextRange(token.GetTreeStartOffset());
            var originalTokenRange  = rangeTranslator.GeneratedToOriginal(generatedTokenRange);
            var t4Element           = rangeTranslator.OriginalFile.FindNodeAt(originalTokenRange);
            var otherCodeBlock      = t4Element?.GetParentOfType <IT4CodeBlock>();

            if (otherCodeBlock == null)
            {
                return(null);
            }
            return(tokenRange.GetIndentFromDocumentRange());
        }
Exemplo n.º 24
0
        public IChameleonNode ReSync(CachingLexer cachingLexer, TreeTextRange changedRange, int insertedTextLen)
        {
            var currentStartOffset = GetTreeStartOffset();
            var currentLength      = GetTextLength();

            Assertion.Assert(
                changedRange.StartOffset >= currentStartOffset && changedRange.EndOffset <= currentStartOffset + currentLength,
                "changedRange.StartOffset >= currentStartOffset && changedRange.EndOffset <= (currentStartOffset+currentLength)");

            var newLength = currentLength - changedRange.Length + insertedTextLen;

            // Can we resync from the start point?
            if (!cachingLexer.FindTokenAt(currentStartOffset.Offset) ||
                cachingLexer.TokenStart != currentStartOffset.Offset ||
                !IsAtValidStartToken(cachingLexer))
            {
                return(null);
            }

            // Try to find a valid end point
            TokenNodeType tokenType;
            var           calculatedNewLength = 0;

            while ((tokenType = cachingLexer.TokenType) != null &&
                   (calculatedNewLength += cachingLexer.TokenEnd - cachingLexer.TokenStart) < newLength)
            {
                // We shouldn't encounter these until the end of the changed range
                if (tokenType == YamlTokenType.DOCUMENT_END || tokenType == YamlTokenType.DIRECTIVES_END)
                {
                    return(null);
                }

                cachingLexer.Advance();
            }

            if (calculatedNewLength != newLength || !IsAtValidEndToken(cachingLexer))
            {
                return(null);
            }

            // TODO: Should this be synchronised?
            // The C# implementation isn't...
            if (!myOpened)
            {
                var buffer = ProjectedBuffer.Create(cachingLexer.Buffer,
                                                    new TextRange(currentStartOffset.Offset, currentStartOffset.Offset + newLength));
                var closedChameleon = new ClosedChameleonElement(YamlTokenType.CHAMELEON, buffer, TreeOffset.Zero,
                                                                 new TreeOffset(buffer.Length));
                return(new ChameleonDocumentBody(closedChameleon));
            }

            var projectedLexer = new ProjectedLexer(cachingLexer, new TextRange(currentStartOffset.Offset, currentStartOffset.Offset + newLength));
            var parser         =
                (IYamlParser)Language.LanguageService().CreateParser(projectedLexer, GetPsiModule(), GetSourceFile());

            var openedChameleon = parser.ParseDocumentBody();

            return(new ChameleonDocumentBody(openedChameleon));
        }
Exemplo n.º 25
0
        protected DocumentRange?FindTrueDocumentRange(TreeTextRange range)
        {
            var ranges = CodeFile.GetIntersectingRanges(range)
                         .Where(x => x.Document == PsiSourceFile.Document)
                         .ToList();

            return(ranges.Count == 0 ? (DocumentRange?)null : ranges[0]);
        }
 public override void FindNodesAtInternal(TreeTextRange relativeRange, List <ITreeNode> result,
                                          bool includeContainingNodes)
 {
     if (relativeRange.ContainedIn(TreeTextRange.FromLength(GetTextLength())))
     {
         base.FindNodesAtInternal(relativeRange, result, includeContainingNodes);
     }
 }
Exemplo n.º 27
0
        public override IChameleonNode FindChameleonWhichCoversRange(TreeTextRange textRange)
        {
            if (textRange.ContainedIn(TreeTextRange.FromLength(GetTextLength())))
            {
                return(base.FindChameleonWhichCoversRange(textRange) ?? this);
            }

            return(null);
        }
Exemplo n.º 28
0
        public override ITreeNode FindNodeAt(TreeTextRange treeRange)
        {
            if (treeRange.IntersectsOrContacts(TreeTextRange.FromLength(GetTextLength())))
            {
                return(base.FindNodeAt(treeRange));
            }

            return(null);
        }
Exemplo n.º 29
0
        private T4FileSector FindSectorAtRange(TreeTextRange range)
        {
            foreach (var sector in Sectors.Where(sector => sector.Range.Contains(range)))
            {
                return(sector);
            }

            return(new T4FileSector(TreeTextRange.InvalidRange, null, 0));
        }
Exemplo n.º 30
0
		/// <summary>
		/// Appends a mapped text.
		/// </summary>
		/// <param name="text">The text to add.</param>
		/// <param name="textRange">The original text range.</param>
		internal void AppendMapped([CanBeNull] string text, TreeTextRange textRange) {
			if (String.IsNullOrEmpty(text))
				return;

			var startOffset = new TreeOffset(_builder.Length);
			_builder.Append(text);
			var endOffset = new TreeOffset(_builder.Length);
			_generatedRangeMap.Add(
				new TreeTextRange<Generated>(startOffset, endOffset),
				new TreeTextRange<Original>(textRange));
		}
Exemplo n.º 31
0
        /// <summary>
        /// Handles the removal of an import directive.
        /// </summary>
        /// <param name="psiServices">The PSI services.</param>
        /// <param name="scope">The namespace scope.</param>
        /// <param name="usingDirective">The using directive to remove.</param>
        /// <param name="action">The action to perform to remove the directive.</param>
        public void HandleRemoveImport(IPsiServices psiServices, ICSharpTypeAndNamespaceHolderDeclaration scope, IUsingDirective usingDirective, Action action)
        {
            ICSharpTreeNode namespaceNode = usingDirective.GetUsedNamespaceNode();

            if (namespaceNode == null)
            {
                Assertion.Fail("Only a namespace using can be removed.");
            }
            else
            {
                TreeTextRange range = namespaceNode.GetTreeTextRange();
                HandleRemoveImportInternal(psiServices, scope, usingDirective, action, CSharpLanguage.Instance, range);
            }
        }
Exemplo n.º 32
0
        public TreeTextRange Translate(DocumentRange documentRange)
        {
            if (!documentRange.IsValid() ||
                _sourceFile == null ||
                !_sourceFile.IsValid())
            {
                return(TreeTextRange.InvalidRange);
            }

            if (documentRange.Document != _sourceFile.Document)
            {
                foreach (IT4Include include in _includes)
                {
                    if (include.DocumentRangeTranslator != null)
                    {
                        TreeTextRange textRange = include.DocumentRangeTranslator.Translate(documentRange);
                        if (textRange.IsValid())
                        {
                            return(textRange);
                        }
                    }
                }
                return(TreeTextRange.InvalidRange);
            }

            TextRange  range           = documentRange.TextRange;
            TreeOffset rootStartOffset = _root.GetTreeStartOffset();

            // no includes, tree and document are matching
            if (_includes.Count == 0)
            {
                return(new TreeTextRange(rootStartOffset + range.StartOffset, rootStartOffset + range.EndOffset));
            }

            TreeOffset startOffset = Translate(range.StartOffset);

            if (!startOffset.IsValid())
            {
                return(TreeTextRange.InvalidRange);
            }

            TreeOffset endOffset = Translate(range.EndOffset);

            if (!endOffset.IsValid())
            {
                return(TreeTextRange.InvalidRange);
            }

            return(new TreeTextRange(startOffset, endOffset));
        }
        public static MethodContractInfo TryCreate(
            [NotNull] IMethodDeclaration declaration, TreeTextRange selectedTreeRange, [NotNull] Func<IType, bool> isAvailableForType)
        {
            if (declaration.GetNameRange().Contains(selectedTreeRange) && declaration.ArrowExpression == null)
            {
                var method = declaration.DeclaredElement;

                if (method != null && CanAcceptContracts(method) && !method.ReturnType.IsVoid() && isAvailableForType(method.ReturnType))
                {
                    return new MethodContractInfo(declaration, method.ReturnType);
                }
            }

            return null;
        }
Exemplo n.º 34
0
        /// <summary>
        /// Appends a mapped text.
        /// </summary>
        /// <param name="text">The text to add.</param>
        /// <param name="textRange">The original text range.</param>
        internal void AppendMapped([CanBeNull] string text, TreeTextRange textRange)
        {
            if (String.IsNullOrEmpty(text))
            {
                return;
            }

            var startOffset = new TreeOffset(_builder.Length);

            _builder.Append(text);
            var endOffset = new TreeOffset(_builder.Length);

            _generatedRangeMap.Add(
                new TreeTextRange <Generated>(startOffset, endOffset),
                new TreeTextRange <Original>(textRange));
        }
        public static OperatorContractInfo TryCreate(
            [NotNull] IOperatorDeclaration declaration, TreeTextRange selectedTreeRange, [NotNull] Func<IType, bool> isAvailableForType)
        {
            if (declaration.GetNameRange().Contains(selectedTreeRange) && declaration.ArrowExpression == null)
            {
                var operatorElement = declaration.DeclaredElement;

                Debug.Assert(operatorElement != null);

                if (CanAcceptContracts(operatorElement) && isAvailableForType(operatorElement.ReturnType))
                {
                    return new OperatorContractInfo(declaration, operatorElement.ReturnType);
                }
            }

            return null;
        }
Exemplo n.º 36
0
        /// <summary>
        /// The process of generated document commit (in the case of primary document incremental reparse) can be overridden in this method.
        ///             Returns null if full regeneration is required.
        ///             This method is not allowed to do destructive changes due to interruptibility!
        /// </summary>
        public override ICollection<IPreCommitResult> ExecuteSecondaryDocumentCommitWork(PrimaryFileModificationInfo primaryFileModificationInfo, CachedPsiFile cachedPsiFile, TreeTextRange oldTreeRange, string newText)
        {
            var rangeTranslator = (RangeTranslatorWithGeneratedRangeMap) cachedPsiFile.PsiFile.SecondaryRangeTranslator;
            if (rangeTranslator == null)
                return null;

            TreeTextRange range = rangeTranslator.OriginalToGenerated(oldTreeRange, JetPredicate<IUserDataHolder>.True);
            DocumentRange documentRange = cachedPsiFile.PsiFile.DocumentRangeTranslator.Translate(range);
            if (!documentRange.IsValid())
                return null;

            var documentChange = new DocumentChange(documentRange.Document, documentRange.TextRange.StartOffset, documentRange.TextRange.Length, newText,
                documentRange.Document.LastModificationStamp, TextModificationSide.NotSpecified);

            return new IPreCommitResult[] {
                new PreCommitResult(cachedPsiFile.WorkIncrementalParse(documentChange), null, documentChange, null, TextRange.InvalidRange, string.Empty),
                new FixRangeTranslatorsOnSharedRangeCommitResult(rangeTranslator, null, new TreeTextRange<Original>(oldTreeRange), new TreeTextRange<Generated>(range), newText)
            };
        }
Exemplo n.º 37
0
    public IChameleonNode ReSync(CachingLexer cachingLexer, TreeTextRange changedRange, int insertedTextLen)
    {
      TreeTextRange oldRange = this.GetTreeTextRange();

      Logger.Assert(changedRange.ContainedIn(oldRange), "The condition “changedRange.ContainedIn(oldRange)” is false.");

      int newLength = oldRange.Length - changedRange.Length + insertedTextLen;
      // Find starting comment
      if (!cachingLexer.FindTokenAt(oldRange.StartOffset.Offset) ||
        cachingLexer.TokenType != GetTokenType() ||
          cachingLexer.TokenStart != oldRange.StartOffset.Offset ||
            cachingLexer.TokenEnd != oldRange.StartOffset.Offset + newLength)
      {
        return null;
      }

      LeafElementBase element = TreeElementFactory.CreateLeafElement(cachingLexer.TokenType, new ProjectedBuffer(cachingLexer.Buffer, new TextRange(cachingLexer.TokenStart, cachingLexer.TokenStart + newLength)), 0, newLength);
      var comment = element as Comment;
      if (comment == null || CommentType != comment.CommentType)
      {
        return null;
      }
      return comment;
    }
Exemplo n.º 38
0
 public override IChameleonNode FindChameleonWhichCoversRange(TreeTextRange textRange)
 {
   return textRange.ContainedIn(TreeTextRange.FromLength(GetTextLength())) ? this : null;
 }
 protected override IReference FindReference(TreeTextRange referenceRange, ITreeNode treeNode)
 {
     return treeNode.FindReferencesAt(referenceRange).FirstOrDefault();
 }
 protected override IReparseContext GetReparseContext(IFile file, TreeTextRange range)
 {
     return new TrivialReparseContext(file, range);
 }
 private static IPathReference GetFolderPathReference(IJavaScriptLiteralExpression literal, IQualifier qualifier,
     IJavaScriptLiteralExpression token, TreeTextRange range)
 {
     return new AngularJsFolderLateBoundReference<IJavaScriptLiteralExpression, IJavaScriptLiteralExpression>(literal, qualifier, token, range);
 }
Exemplo n.º 42
0
 public IDeclarationsRange GetDeclarationsRange(TreeTextRange range)
 {
     return _file.GetDeclarationsRange(range);
 }
 public ICollection<IPreCommitResult> ExecuteSecondaryDocumentCommitWork(PrimaryFileModificationInfo primaryFileModificationInfo, CachedPsiFile cachedPsiFile, TreeTextRange oldTreeRange, string newText)
 {
   return null;
 }
Exemplo n.º 44
0
 public IFile ReParse(TreeTextRange modifiedRange, string text)
 {
     return _file.ReParse(modifiedRange, text);
 }
    public static IEnumerable<string> GetAplicableKeywords(IPsiFile file, TreeTextRange referenceRange)
    {
      // statements part ...
      //var ret = new HashSet<string>();
      IList<string> list = new List<string>();
      var token = file.FindNodeAt(referenceRange) as ITokenNode;
      if (token == null)
      {
        return list;
      }

      ITreeNode currentNode;
      ITreeNode child;

      if (token.GetTokenType() == PsiTokenType.IDENTIFIER && token.Parent != null)
      {
        currentNode = token.Parent.Parent;
        child = token.Parent;
      }
      else
      {
        currentNode = token.Parent;
        child = token;
      }

      if (currentNode is IRuleDeclaration)
      {
        if (!IsInRuleBody(child))
        {
          if (IsAfterName(child))
          {
            list.Add("extras");
            list.Add("options");
          }
          if (IsBeforeName(child))
          {
            list.Add("abstract");
            list.Add("errorhandling");
            list.Add("interface");
            list.Add("private");
          }
          if (HasNoName(child))
          {
            list.Add("interfaces");
            list.Add("paths");
          }
        }
        else
        {
          list.Add("null");
          list.Add("LIST");
          list.Add("SEP");
        }
      }
      else if (currentNode is IExtrasDefinition)
      {
        list.Add("get");
        list.Add("returnType");
        list.Add("isCashed");
      }
      else if (currentNode is ISimpleExpression)
      {
        list.Add("null");
        list.Add("LIST");
        list.Add("SEP");
      }
      else if (currentNode is IListExpression)
      {
        list.Add("SEP");
      }
      else if (currentNode is IRuleParameters)
      {
        list.Add("cashed");
        list.Add("isCashed");
        list.Add("ROLE");
        list.Add("getter");
      }
      return list;
    }
Exemplo n.º 46
0
    public IChameleonNode ReSync(CachingLexer cachingLexer, TreeTextRange changedRange, int insertedTextLen)
    {
      TreeOffset currStartOffset = GetTreeStartOffset();
      int currLength = GetTextLength();

      Logger.Assert(changedRange.StartOffset >= currStartOffset && changedRange.EndOffset <= (currStartOffset + currLength),
        "changedRange.StartOffset >= currStartOffset && changedRange.EndOffset <= (currStartOffset+currLength)");

      int newLength = currLength - changedRange.Length + insertedTextLen;

      LanguageService languageService = Language.LanguageService();
      if (languageService != null)
      {
        var parser = (IPsiParser)languageService.CreateParser(new ProjectedLexer(cachingLexer, new TextRange(currStartOffset.Offset, currStartOffset.Offset + newLength)), GetPsiModule(), GetSourceFile());
        TreeElement newElement = parser.ParseStatement();
        if (newElement.GetTextLength() == 0)
        {
          return null;
        }
        if ((newElement.GetTextLength() == newLength) && (";".Equals(newElement.GetText().Substring(newElement.GetTextLength() - 1))))
        {
          var psiFile = GetContainingNode<PsiFile>();
          if (psiFile != null)
          {
            psiFile.ClearTables();
          }
          return newElement as IRuleDeclaration;
        }
      }
      return null;
    }
Exemplo n.º 47
0
    public override IChameleonNode FindChameleonWhichCoversRange(TreeTextRange textRange)
    {
      if (textRange.ContainedIn(TreeTextRange.FromLength(GetTextLength())))
      {
        return base.FindChameleonWhichCoversRange(textRange) ?? this;
      }

      return null;
    }
 public NTriplesReparsedCompletionContext([NotNull] IFile file, TreeTextRange range, string newText)
     : base(file, range, newText)
 {
 }
 public void ProcessChangeFromPrimaryToGenerated(TreeTextRange range, string oldText, string newText, ISecondaryRangeTranslator rangeTranslator, IFile file, IPsiTransactionAction transactionAction)
 {
 }
Exemplo n.º 50
0
		public DocumentRange[] GetIntersectedOriginalRanges(TreeTextRange range) {
			return new[] { Translate(range) };
		}
Exemplo n.º 51
0
 public PsiFileModificationInfo GetReParseResult(TreeTextRange modifiedRange, string text)
 {
     return _file.GetReParseResult(modifiedRange, text);
 }
Exemplo n.º 52
0
 public override IChameleonNode ReSync(CachingLexer cachingLexer, TreeTextRange changedRange, int insertedTextLen)
 {
     return base.ReSync(cachingLexer, changedRange, insertedTextLen) as DocComment;
 }
Exemplo n.º 53
0
 /// <summary>
 /// Reparses the original T4 file.
 /// </summary>
 /// <param name="treeTextRange">The tree text range to reparse.</param>
 /// <param name="newText">The new text to add at <paramref name="treeTextRange"/>.</param>
 /// <param name="rangeTranslator">The range translator.</param>
 /// <returns><c>true</c> if reparse succeeded, <c>false</c> otherwise.</returns>
 protected override bool ReparseOriginalFile(TreeTextRange treeTextRange, string newText, RangeTranslatorWithGeneratedRangeMap rangeTranslator)
 {
     var t4File = rangeTranslator.OriginalFile as IT4File;
     return t4File != null && t4File.ReParse(treeTextRange, newText) != null;
 }