3
3
const tokenize = require ( "kuromojin" ) . tokenize ;
4
4
const dictionaryList = require ( "./dictionary" ) ;
5
5
const createMatchAll = require ( "morpheme-match-all" ) ;
6
- const replaceWithCaptureTokens = ( text , tokens , actualTokens ) => {
6
+
7
+ const replaceTokenWith = ( matcherToken , actualToken , specialTo ) => {
8
+ // _captureがないのは無視
9
+ if ( ! matcherToken . _capture ) {
10
+ return null ;
11
+ }
12
+ if ( matcherToken [ specialTo ] ) {
13
+ return matcherToken [ specialTo ] ( actualToken ) ;
14
+ }
15
+ return actualToken . surface_form ;
16
+ } ;
17
+ const createExpected = ( { text, matcherTokens, actualTokens} ) => {
18
+ let resultText = text ;
19
+ matcherTokens . forEach ( ( token , index ) => {
20
+ const to = replaceTokenWith ( token , actualTokens [ index ] , "_capture_to_expected" ) ;
21
+ if ( to !== null ) {
22
+ resultText = resultText . split ( token . _capture ) . join ( to ) ;
23
+ }
24
+ } ) ;
25
+ return resultText ;
26
+ } ;
27
+ const createMessage = ( { text, matcherTokens, actualTokens} ) => {
7
28
let resultText = text ;
8
- tokens . forEach ( ( token , index ) => {
9
- // _captureがないのは無視
10
- if ( ! token . _capture ) {
11
- return ;
29
+ matcherTokens . forEach ( ( token , index ) => {
30
+ const to = replaceTokenWith ( token , actualTokens [ index ] , "_capture_to_message" ) ;
31
+ if ( to !== null ) {
32
+ resultText = resultText . split ( token . _capture ) . join ( to ) ;
12
33
}
13
- const actualToken = actualTokens [ index ] ;
14
- resultText = resultText . split ( token . _capture ) . join ( actualToken . surface_form ) ;
15
34
} ) ;
16
35
return resultText ;
17
36
} ;
37
+
18
38
const reporter = ( context ) => {
19
39
const { Syntax, RuleError, report, fixer, getSource} = context ;
20
40
const matchAll = createMatchAll ( dictionaryList ) ;
@@ -32,10 +52,18 @@ const reporter = (context) => {
32
52
const firstWordIndex = Math . max ( firstToken . word_position - 1 , 0 ) ;
33
53
const lastWorkIndex = Math . max ( lastToken . word_position - 1 , 0 ) ;
34
54
// replace $1
35
- const message = replaceWithCaptureTokens ( matchResult . dict . message , matchResult . dict . tokens , matchResult . tokens )
55
+ const message = createMessage ( {
56
+ text : matchResult . dict . message ,
57
+ matcherTokens : matchResult . dict . tokens ,
58
+ actualTokens : matchResult . tokens
59
+ } )
36
60
+ ( matchResult . dict . url ? `参考: ${ matchResult . dict . url } ` : "" ) ;
37
61
const expected = matchResult . dict . expected
38
- ? replaceWithCaptureTokens ( matchResult . dict . expected , matchResult . dict . tokens , matchResult . tokens )
62
+ ? createExpected ( {
63
+ text : matchResult . dict . expected ,
64
+ matcherTokens : matchResult . dict . tokens ,
65
+ actualTokens : matchResult . tokens
66
+ } )
39
67
: undefined ;
40
68
if ( expected ) {
41
69
report ( node , new RuleError ( message , {
0 commit comments