1+ import { VersionExpressionSets as SlangVersionExpressionSets } from '@nomicfoundation/slang/ast' ;
12import { NonterminalKind , Query } from '@nomicfoundation/slang/cst' ;
23import { Parser } from '@nomicfoundation/slang/parser' ;
3- import strip from 'strip-comments' ;
44import {
55 maxSatisfying ,
66 minSatisfying ,
99 satisfies ,
1010 validRange
1111} from 'semver' ;
12+ import { VersionExpressionSets } from '../slang-nodes/VersionExpressionSets.js' ;
13+
14+ import type { ParserOptions } from 'prettier' ;
1215
1316const supportedVersions = Parser . supportedVersions ( ) ;
1417
@@ -25,10 +28,14 @@ const milestoneVersions = Array.from(
2528 return versions ;
2629 } , [ ] ) ;
2730
31+ const query = Query . parse (
32+ '[VersionPragma @versionRanges [VersionExpressionSets]]'
33+ ) ;
34+
2835// TODO if we ended up selecting the same version that the pragmas were parsed with,
2936// should we be able to reuse/just return the already parsed CST, instead of
3037// returning a Parser and forcing user to parse it again?
31- export function createParser ( text : string ) : Parser {
38+ export function createParser ( text : string , options : ParserOptions ) : Parser {
3239 let inferredRanges : string [ ] = [ ] ;
3340
3441 for ( const version of milestoneVersions ) {
@@ -42,7 +49,7 @@ export function createParser(text: string): Parser {
4249 ( versions , inferredRange ) => {
4350 if ( ! validRange ( inferredRange ) ) {
4451 throw new Error (
45- " Couldn't infer any version from the ranges in the pragmas."
52+ ` Couldn't infer any version from the ranges in the pragmas${ options . filepath ? ` for file ${ options . filepath } ` : '' } `
4653 ) ;
4754 }
4855 return versions . filter ( ( supportedVersion ) =>
@@ -60,18 +67,20 @@ export function createParser(text: string): Parser {
6067function tryToCollectPragmas ( text : string , version : string ) : string [ ] {
6168 const language = Parser . create ( version ) ;
6269 const parseOutput = language . parse ( NonterminalKind . SourceUnit , text ) ;
63- const query = Query . parse (
64- '[VersionPragma @versionRanges [VersionExpressionSets]]'
65- ) ;
6670 const matches = parseOutput . createTreeCursor ( ) . query ( [ query ] ) ;
6771 const ranges : string [ ] = [ ] ;
6872
6973 let match ;
7074 while ( ( match = matches . next ( ) ) ) {
75+ const versionRange = new SlangVersionExpressionSets (
76+ match . captures . versionRanges [ 0 ] . node . asNonterminalNode ( ) !
77+ ) ;
7178 ranges . push (
72- strip ( match . captures . versionRanges [ 0 ] . node . unparse ( ) , {
73- keepProtected : true
74- } )
79+ // Replace all comments that could be in the expression with whitespace
80+ new VersionExpressionSets ( versionRange ) . comments . reduce (
81+ ( range , comment ) => range . replace ( comment . value , ' ' ) ,
82+ versionRange . cst . unparse ( )
83+ )
7584 ) ;
7685 }
7786
0 commit comments