@ -37,24 +37,40 @@ function generateJavascript(ast, options) {
}
}
function generateCacheHeader ( ruleIndexCode ) {
return [
'var key = peg$currPos * ' + ast . rules . length + ' + ' + ruleIndexCode + ',' ,
' cached = peg$cache[key];' ,
'' ,
'if (cached) {' ,
' peg$currPos = cached.nextPos;' ,
' return cached.result;' ,
'}' ,
''
] . join ( '\n' ) ;
function generateRuleHeader ( ruleIndexCode ) {
if ( options . cache ) {
return [
'' ,
'var key = peg$currPos * ' + ast . rules . length + ' + ' + ruleIndexCode + ',' ,
' cached = peg$cache[key];' ,
'' ,
'if (cached) {' ,
' peg$currPos = cached.nextPos;' ,
' return cached.result;' ,
'}' ,
''
] . join ( '\n' ) ;
} else {
return '' ;
}
}
function generateCacheFooter ( resultCode ) {
return [
function generateRuleFooter ( resultCode ) {
var parts = [ ] ;
if ( options . cache ) {
parts . push ( [
'' ,
'peg$cache[key] = { nextPos: peg$currPos, result: ' + resultCode + ' };'
] . join ( '\n' ) ) ;
}
parts . push ( [
'' ,
'peg$cache[key] = { nextPos: peg$currPos, result: ' + resultCode + ' };'
] . join ( '\n' ) ;
'return ' + resultCode + ';'
] . join ( '\n' ) ) ;
return parts . join ( '\n' ) ;
}
function generateInterpreter ( ) {
@ -140,12 +156,9 @@ function generateJavascript(ast, options) {
' ends = [],' ,
' stack = [],' ,
' params, i;' ,
''
] . join ( '\n' ) ) ;
if ( options . cache ) {
parts . push ( indent2 ( generateCacheHeader ( 'index' ) ) ) ;
}
parts . push ( indent2 ( generateRuleHeader ( 'index' ) ) ) ;
parts . push ( [
/ *
@ -324,15 +337,8 @@ function generateJavascript(ast, options) {
' }'
] . join ( '\n' ) ) ;
if ( options . cache ) {
parts . push ( indent2 ( generateCacheFooter ( 'stack[0]' ) ) ) ;
}
parts . push ( [
'' ,
' return stack[0];' ,
'}'
] . join ( '\n' ) ) ;
parts . push ( indent2 ( generateRuleFooter ( 'stack[0]' ) ) ) ;
parts . push ( '}' ) ;
return parts . join ( '\n' ) ;
}
@ -649,26 +655,13 @@ function generateJavascript(ast, options) {
parts . push ( [
'function peg$parse' + rule . name + '() {' ,
' var ' + arrays . map ( arrays . range ( 0 , stack . maxSp + 1 ) , s ) . join ( ', ' ) + ';' ,
''
] . join ( '\n' ) ) ;
if ( options . cache ) {
parts . push ( indent2 (
generateCacheHeader ( asts . indexOfRule ( ast , rule . name ) )
) ) ;
}
parts . push ( indent2 ( generateRuleHeader ( asts . indexOfRule ( ast , rule . name ) ) ) ) ;
parts . push ( indent2 ( code ) ) ;
parts . push ( indent2 ( generateRuleFooter ( s ( 0 ) ) ) ) ;
if ( options . cache ) {
parts . push ( indent2 ( generateCacheFooter ( s ( 0 ) ) ) ) ;
}
parts . push ( [
'' ,
' return ' + s ( 0 ) + ';' ,
'}'
] . join ( '\n' ) ) ;
parts . push ( '}' ) ;
return parts . join ( '\n' ) ;
}