2017-05-02 4 views
0

sweet.js가 생성하는 출력에 임의의 문자열을 삽입하는 방법은 무엇입니까?임의 문자열을 sweet.js 출력에 삽입

이것은 다양한 조건에 따라 문자열이 다른 곳에서 프로그램 적으로 작업 할 때 매우 유용합니다.

예를 들어, 아래 코드의 25 행에 결과로 문자열을 삽입하고 싶습니다.

sweet.js 코드 :

import { produceNormalParams } from './abc/produceNormalParams' 
    import { produceParamChecks } from './abc/produceParamChecks' 
    import { produceInnerChecks } from './abc/produceInnerChecks' 

    syntax function = function(ctx) { 
     let funcName = ctx.next().value; 
     let funcParams = ctx.next().value; 
     let funcBody = ctx.next().value; 

     //produce the normal params array 
     var normalParams = produceNormalParams(funcParams) 

     //produce the checks 
     var paramChecks = produceParamChecks(funcParams) 

     //produce the original funcBody code 
     var inner = produceInnerChecks(funcParams) 

     var someArbitraryString = "console.log('hey')" 

     //put them together as the final result 
     var result = #`function ${funcName} ${normalParams} { 
      ${someArbitraryString} 
      ${paramChecks} 
      ${inner} 
     }` 

     return result 
    } 

예 입력 :

module.exports = multiply 

    function multiply(a:array,b,c:array) { 
     return a * c 
    } 

예 출력 :

// Example Output 
    module.exports = multiply; 
    function multiply(a_31, b_32, c_33) { 
     console.log('hey') 
     if (Object.prototype.toString.call(a_31) !== "[object Array]") throw new Error("Must be array:" + a_31); 
     if (Object.prototype.toString.call(c_33) !== "[object Array]") throw new Error("Must be array:" + c_33); 
     return a_31 * c_33; 
    } 

답변

1

당신이 구문 템플릿에 임의의 문자열을 삽입 할 수는 없지만, 당신은 다른 구문 템플릿을 보간 할 수 있습니다.

import { produceNormalParams } from './abc/produceNormalParams' for syntax; 
import { produceParamChecks } from './abc/produceParamChecks' for syntax; 
import { produceInnerChecks } from './abc/produceInnerChecks' for syntax; 

syntax function = function(ctx) { 
    let funcName = ctx.next().value; 
    let funcParams = ctx.next().value; 
    let funcBody = ctx.next().value; 

    //produce the normal params array 
    var normalParams = produceNormalParams(funcParams); 

    //produce the checks 
    var paramChecks = produceParamChecks(funcParams); 

    //produce the original funcBody code 
    var inner = produceInnerChecks(funcParams); 

    var someArbitrarySyntax = #`console.log('hey')`; 

    //put them together as the final result 
    var result = #`function ${funcName} ${normalParams} { 
     ${someArbitrarySyntax} 
     ${paramChecks} 
     ${inner} 
    }`; 

    return result 
} 

참고 for syntax 가져 오기 문을 후행. 이는 컴파일 시간 동안 가져 오기가 가능하기 위해 필요합니다.

+0

예제가 작동합니다. 그러나 프로그래밍 방식으로 생성 된 기존 문자열을 가져올 수 있습니까? 예 : function getString() {return 'abcdef'} 그리고 구문으로 변환하십시오. 기본적으로 라이브러리에 일부 매개 변수를 전달하고 라이브러리에서 문자열을 반환 한 다음 해당 문자열을 삽입합니다. –

+0

현재는 아닙니다. 그것이 여러분의 라이브러리이고 다른 컨텍스트에서 사용하지 않는다면 문자열 대신 구문 템플릿을 반환 할 수 있습니다. –