UNPKG

1.62 kBJavaScriptView Raw
1export default function analyse ( magicString, module ) {
2 // first we need to generate comprehensive scope info
3 let previousStatement = null;
4 let commentIndex = 0;
5
6 module.statements.forEach( statement => {
7 const node = statement.node;
8
9 let trailing = !!previousStatement;
10
11 // TODO surely this can be neater
12 // attach leading comment
13 do {
14 let comment = module.comments[ commentIndex ];
15
16 // prevent comments inside the previous statement being
17 // appended to it
18 if ( previousStatement ) {
19 while ( comment && comment.start < previousStatement.node.end ) {
20 commentIndex += 1;
21 comment = module.comments[ commentIndex ];
22 }
23 }
24
25 if ( !comment || ( comment.end > node.start ) ) break;
26
27 // attach any trailing comment to the previous statement
28 if ( trailing && !/\n/.test( module.source.slice( previousStatement.node.end, comment.start ) ) ) {
29 previousStatement.trailingComment = comment;
30 }
31
32 // then attach leading comments to this statement
33 else {
34 statement.leadingComments.push( comment );
35 }
36
37 commentIndex += 1;
38 trailing = false;
39 } while ( module.comments[ commentIndex ] );
40
41 // determine margin
42 const previousEnd = previousStatement ? ( previousStatement.trailingComment || previousStatement.node ).end : 0;
43 const start = ( statement.leadingComments[0] || node ).start;
44
45 const gap = magicString.original.slice( previousEnd, start );
46 const margin = gap.split( '\n' ).length;
47
48 if ( previousStatement ) previousStatement.margin[1] = margin;
49 statement.margin[0] = margin;
50
51 statement.analyse();
52
53 previousStatement = statement;
54 });
55}