/******************************************************************************
 * Copyright 2021 TypeFox GmbH
 * This program and the accompanying materials are made available under the
 * terms of the MIT License, which is available in the project root.
 ******************************************************************************/ import { IToken } from '@chevrotain/types' ; import { Range } from 'vscode-languageserver' ; import { CompositeCstNodeImpl , LeafCstNodeImpl } from '../parser/cst-node-builder' ; import { DatatypeSymbol } from '../parser/langium-parser' ; import { AstNode , CstNode , LeafCstNode } from '../syntax-tree' ; import { DocumentSegment } from '../workspace/documents' ; import { TreeStream , TreeStreamImpl } from './stream' ; export function streamCst ( node ) { return new TreeStreamImpl ( node , element => { if ( element instanceof CompositeCstNodeImpl ) { return element . children ; } else { return [ ] ; } } ) ; } export function flatten ( node ) { if ( node instanceof LeafCstNodeImpl ) { return [ node ] ; } else if ( node instanceof CompositeCstNodeImpl ) { return node . children . flatMap ( e => flatten ( e ) ) ; } else { return [ ] ; } } export function tokenToRange ( token ) { return { start : { character : token . startColumn ! - 1 , line : token . startLine ! - 1 } , end : { character : token . endColumn ! , line : token . endLine ! - 1 } } ; } export function toDocumentSegment ( node ) { const { offset , end , range } = node ; return { range , offset , end , length : end - offset } ; } export function findRelevantNode ( cstNode ) { let n = cstNode ; do { const element = n . element as any ; if ( element . $type !== DatatypeSymbol ) { return element ; } n = n . parent ; } while ( n ) ; return undefined ; } export function findCommentNode ( cstNode , commentNames ) { let lastNode ; if ( cstNode instanceof CompositeCstNodeImpl ) { for ( const node of cstNode . children ) { if ( ! node . hidden ) { break ; } if ( node instanceof LeafCstNodeImpl && commentNames . includes ( node . tokenType . name ) ) { lastNode = node ; } } } return lastNode ; }