2016-04-06 16:22:30 +00:00
( function ( f ) { if ( typeof exports === "object" && typeof module !== "undefined" ) { module . exports = f ( ) } else if ( typeof define === "function" && define . amd ) { define ( [ ] , f ) } else { var g ; if ( typeof window !== "undefined" ) { g = window } else if ( typeof global !== "undefined" ) { g = global } else if ( typeof self !== "undefined" ) { g = self } else { g = this } g . SyndicateCompiler = f ( ) } } ) ( function ( ) { var define , module , exports ; return ( function e ( t , n , r ) { function s ( o , u ) { if ( ! n [ o ] ) { if ( ! t [ o ] ) { var a = typeof require == "function" && require ; if ( ! u && a ) return a ( o , ! 0 ) ; if ( i ) return i ( o , ! 0 ) ; var f = new Error ( "Cannot find module '" + o + "'" ) ; throw f . code = "MODULE_NOT_FOUND" , f } var l = n [ o ] = { exports : { } } ; t [ o ] [ 0 ] . call ( l . exports , function ( e ) { var n = t [ o ] [ 1 ] [ e ] ; return s ( n ? n : e ) } , l , l . exports , e , t , n , r ) } return n [ o ] . exports } var i = typeof require == "function" && require ; for ( var o = 0 ; o < r . length ; o ++ ) s ( r [ o ] ) ; return s } ) ( { 1 : [ function ( require , module , exports ) {
( function ( Buffer ) {
// Compile ES5+Syndicate to plain ES5.
'use strict' ;
var path = require ( 'path' ) ;
var ohm = require ( 'ohm-js' ) ;
var ES5 = require ( './es5.js' ) ;
2017-02-20 22:19:56 +00:00
var grammarSource = Buffer ( " Ly8gLSotIGphdmFzY3JpcHQgLSotCi8vIFN5bnRhY3RpYyBleHRlbnNpb25zIHRvIEVTNSBmb3IgU3luZGljYXRlL2pzLiBTZWUgY29tcGlsZXIuanMgZm9yCi8vIHRoZSByZXN0IG9mIHRoZSB0cmFuc2xhdG9yLgoKU3luZGljYXRlIDw6IEVTNSB7CiAgLy8tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0KICAvLyBFeHRlbnNpb25zIHRvIGV4cHJlc3Npb25zLgoKICBTdGF0ZW1lbnQKICAgICs9IEFjdG9yU3RhdGVtZW50CiAgICB8IERhdGFzcGFjZVN0YXRlbWVudAogICAgfCBBY3RvckZhY2V0U3RhdGVtZW50CiAgICB8IEFjdG9yRW5kcG9pbnRTdGF0ZW1lbnQKICAgIHwgQXNzZXJ0aW9uVHlwZURlY2xhcmF0aW9uU3RhdGVtZW50CiAgICB8IEZpZWxkRGVjbGFyYXRpb25TdGF0ZW1lbnQKICAgIHwgU2VuZE1lc3NhZ2VTdGF0ZW1lbnQKCiAgRnVuY3Rpb25Cb2R5QmxvY2sgPSAieyIgRnVuY3Rpb25Cb2R5ICJ9IiAgIC8vIG9kZCB0aGF0IHRoaXMgaXNuJ3QgaW4gZXM1Lm9obSBzb21ld2hlcmUKCiAgQWN0b3JTdGF0ZW1lbnQKICAgID0gc3Bhd25TdGFyIChuYW1lZCBFeHByZXNzaW9uPHdpdGhJbj4pPyBGdW5jdGlvbkJvZHlCbG9jayAtLSBub1JlYWN0CiAgICB8IHNwYXduIChuYW1lZCBFeHByZXNzaW9uPHdpdGhJbj4pPyBGdW5jdGlvbkJvZHlCbG9jayAgICAgLS0gd2l0aFJlYWN0CgogIERhdGFzcGFjZVN0YXRlbWVudAogICAgPSBncm91bmQgZGF0YXNwYWNlIGlkZW50aWZpZXI / IEZ1bmN0aW9uQm9keUJsb2NrIC0tIGdyb3VuZAogICAgfCBkYXRhc3BhY2UgRnVuY3Rpb25Cb2R5QmxvY2sgICAgICAgICAgICAgICAgICAgIC0tIG5vcm1hbAoKICBBY3RvckZhY2V0U3RhdGVtZW50CiAgICA9IHJlYWN0IEZ1bmN0aW9uQm9keUJsb2NrCgogIEFjdG9yRW5kcG9pbnRTdGF0ZW1lbnQKICAgID0gb24gc3RhcnQgRnVuY3Rpb25Cb2R5QmxvY2sgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgLS0gc3RhcnQKICAgIHwgb24gc3RvcCBGdW5jdGlvbkJvZHlCbG9jayAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgLS0gc3RvcAogICAgfCBhc3NlcnQgRmFjZXRQYXR0ZXJuIEFzc2VydFdoZW5DbGF1c2U / ICMoc2MpICAgICAgICAgICAgICAgICAgICAgICAgICAgICAtLSBhc3NlcnQKICAgIHwgb24gRmFjZXRFdmVudFBhdHRlcm4gRnVuY3Rpb25Cb2R5QmxvY2sgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgLS0gZXZlbnQKICAgIHwgb24gZXZlbnQgaWRlbnRpZmllciBGdW5jdGlvbkJvZHlCbG9jayAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgLS0gb25FdmVudAogICAgfCBzdG9wIG9uIEZhY2V0VHJhbnNpdGlvbkV2ZW50UGF0dGVybiBGdW5jdGlvbkJvZHlCbG9jayAgICAgICAgICAgICAgICAgICAtLSBzdG9wT25XaXRoQ29udAogICAgfCBzdG9wIG9uIEZhY2V0VHJhbnNpdGlvbkV2ZW50UGF0dGVybiAjKHNjKSAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAtLSBzdG9wT25Ob0NvbnQKICAgIHwgZGF0YWZsb3cgRnVuY3Rpb25Cb2R5QmxvY2sgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgLS0gZGF0YWZsb3cKICAgIHwgZHVyaW5nIEZhY2V0UGF0dGVybiBGdW5jdGlvbkJvZHlCbG9jayAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgLS0gZHVyaW5nCiAgICB8IGR1cmluZyBGYWNldFBhdHRlcm4gc3Bhd24gKG5hbWVkIEV4cHJlc3Npb248d2l0aEluPik / IEZ1bmN0aW9uQm9keUJsb2NrIC0tIGR1cmluZ1NwYXduCgogIEFzc2VydFdoZW5DbGF1c2UgPSB3aGVuICIoIiBFeHByZXNzaW9uPHdpdGhJbj4gIikiCgogIEFzc2VydGlvblR5cGVEZWNsYXJhdGlvblN0YXRlbWVudAogICAgPSAoYXNzZXJ0aW9uIHwgbWVzc2FnZSkgdHlwZSBpZGVudGlmaWVyICIoIiBGb3JtYWxQYXJhbWV0ZXJMaXN0ICIpIiAoIj0iIHN0cmluZ0xpdGVyYWwpPyAjKHNjKQoKICBGaWVsZERlY2xhcmF0aW9uU3RhdGVtZW50ID0gZmllbGQgTWVtYmVyRXhwcmVzc2lvbiAoIj0iIEFzc2lnbm1lbnRFeHByZXNzaW9uPHdpdGhJbj4pPyAjKHNjKQogIE1lbWJlckV4cHJlc3Npb24gKz0gZmllbGQgTWVtYmVyRXhwcmVzc2lvbiAtLSBmaWVsZFJlZkV4cAogIFVuYXJ5RXhwcmVzc2lvbiArPSBkZWxldGUgZmllbGQgTWVtYmVyRXhwcmVzc2lvbiAtLSBmaWVsZERlbEV4cAoKICBTZW5kTWVzc2FnZVN0YXRlbWVudCA9ICI6OiIgRXhwcmVzc2lvbjx3aXRoSW4 + ICMoc2MpCgogIEZhY2V0RXZlbnRQYXR0ZXJuCiAgICA9IG1lc3NhZ2UgRmFjZXRQYXR0ZXJuICAgLS0gbWVzc2FnZUV2ZW50CiAgICB8IGFzc2VydGVkIEZhY2V0UGF0dGVybiAgLS0gYXNzZXJ0ZWRFdmVudAogICAgfCByZXRyYWN0ZWQgRmFjZXRQYXR0ZXJuIC0tIHJldHJhY3RlZEV2ZW50CgogIEZhY2V0VHJhbnNpdGlvbkV2ZW50UGF0dGVybgogICAgPSBGYWNldEV2ZW50UGF0dGVybiAgICAgICAgICAtLSBmYWNldEV2ZW50CiAgICB8ICIoIiBFeHByZXNzaW9uPHdpdGhJbj4gIikiIC0tIHJpc2luZ0VkZ2UKCiAgRmFjZXRQYXR0ZXJuCiAgICA9IExlZnRIYW5kU2lkZUV4cHJlc3Npb24gbWV0YWxldmVsIGRlY2ltYWxJbnRlZ2VyTGl0ZXJhbCAtLSB3aXRoTWV0YWxldmVsCiAgICB8IExlZnRIYW5kU2lkZUV4cHJlc3Npb24gICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAtLSBub01ldGFsZXZlbAoKICAvLy0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLQogIC8vIEtleXdvcmRzLiBXZSBkb24ndCBhZGQgdGhlbSB0byB0aGUgImtleXdvcmQiIHByb2R1Y3Rpb24gYmVjYXVzZQogIC8vIHdlIGRvbid0IHdhbnQgdG8gbWFrZSB0aGVtIHVuYXZhaWxhYmxlIHRvIHByb2dyYW1zIGFzCiAgLy8gaWRlbnRpZmllcnMuCgogIHNwYXduU3RhciA9ICJzcGF3bioiIH5pZGVudGlmaWVyUGFydAogIHNwYXduID0gInN
2016-04-06 16:22:30 +00:00
var grammar = ohm . grammar ( grammarSource , { ES5 : ES5 . grammar } ) ;
var semantics = grammar . extendSemantics ( ES5 . semantics ) ;
var gensym _start = Math . floor ( new Date ( ) * 1 ) ;
var gensym _counter = 0 ;
function gensym ( label ) {
return '_' + ( label || 'g' ) + gensym _start + '_' + ( gensym _counter ++ ) ;
}
var forEachChild = ( function ( ) {
function flattenIterNodes ( nodes , acc ) {
for ( var i = 0 ; i < nodes . length ; ++ i ) {
if ( nodes [ i ] . isIteration ( ) ) {
flattenIterNodes ( nodes [ i ] . children , acc ) ;
} else {
acc . push ( nodes [ i ] ) ;
}
}
}
function compareByInterval ( node , otherNode ) {
return node . interval . startIdx - otherNode . interval . startIdx ;
}
function forEachChild ( children , f ) {
var nodes = [ ] ;
flattenIterNodes ( children , nodes ) ;
nodes . sort ( compareByInterval ) . forEach ( f ) ;
}
return forEachChild ;
} ) ( ) ;
2016-08-25 12:13:44 +00:00
function buildActor ( nameExpOpt , block , withReact ) {
2016-05-19 17:15:06 +00:00
var nameExpStr ;
if ( nameExpOpt . numChildren === 1 ) {
nameExpStr = ', ' + nameExpOpt . asES5 ;
} else {
nameExpStr = '' ;
}
2016-08-25 12:13:44 +00:00
return 'Syndicate.Actor.spawnActor(function() ' +
( withReact ? reactWrap ( block . asES5 ) : block . asES5 ) +
nameExpStr + ');' ;
2016-04-06 16:22:30 +00:00
}
2016-08-25 12:13:44 +00:00
function reactWrap ( blockCode ) {
2017-02-20 22:19:56 +00:00
return '{ Syndicate.Actor.Facet.build(function () { ' +
2016-08-25 12:13:44 +00:00
blockCode +
2017-02-20 22:19:56 +00:00
' }); }' ;
2016-04-06 16:22:30 +00:00
}
function buildOnEvent ( isTerminal , eventType , subscription , projection , bindings , body ) {
2016-08-25 12:13:44 +00:00
return 'Syndicate.Actor.Facet.current.onEvent(Syndicate.Actor.PRIORITY_NORMAL, ' + isTerminal + ', ' +
JSON . stringify ( eventType ) + ', ' +
2016-04-06 16:22:30 +00:00
subscription + ', ' + projection +
2016-08-25 12:13:44 +00:00
', (function(' + bindings . join ( ', ' ) + ') ' + body + '));' ;
2016-04-06 16:22:30 +00:00
}
function buildCaseEvent ( eventPattern , body ) {
if ( eventPattern . eventType === 'risingEdge' ) {
return buildOnEvent ( true ,
eventPattern . eventType ,
'function() { return (' + eventPattern . asES5 + '); }' ,
'null' ,
[ ] ,
body ) ;
} else {
return buildOnEvent ( true ,
eventPattern . eventType ,
eventPattern . subscription ,
eventPattern . projection ,
eventPattern . bindings ,
body ) ;
}
}
var modifiedSourceActions = {
2017-02-20 22:19:56 +00:00
ActorStatement _noReact : function ( _spawnStar , _namedOpt , nameExpOpt , block ) {
2016-08-25 12:13:44 +00:00
return buildActor ( nameExpOpt , block , false ) ;
} ,
2017-02-20 22:19:56 +00:00
ActorStatement _withReact : function ( _spawn , _namedOpt , nameExpOpt , block ) {
2016-08-25 12:13:44 +00:00
return buildActor ( nameExpOpt , block , true ) ;
2016-04-06 16:22:30 +00:00
} ,
2016-04-07 07:44:34 +00:00
DataspaceStatement _ground : function ( _ground , _dataspace , maybeId , block ) {
2016-04-06 16:22:30 +00:00
var code = 'new Syndicate.Ground(function () ' + block . asES5 + ').startStepping();' ;
if ( maybeId . numChildren === 1 ) {
return 'var ' + maybeId . children [ 0 ] . interval . contents + ' = ' + code ;
} else {
return code ;
}
} ,
2016-04-07 07:44:34 +00:00
DataspaceStatement _normal : function ( _dataspace , block ) {
return 'Syndicate.Dataspace.spawn(new Dataspace(function () ' + block . asES5 + '));' ;
2016-04-06 16:22:30 +00:00
} ,
2016-08-25 12:13:44 +00:00
ActorFacetStatement : function ( _react , block ) {
return '(function () ' + reactWrap ( block . asES5 ) + ').call(this);' ;
2016-04-06 16:22:30 +00:00
} ,
AssertionTypeDeclarationStatement : function ( _assertion ,
_type ,
typeName ,
_leftParen ,
formalsRaw ,
_rightParen ,
_maybeEquals ,
maybeLabel ,
_maybeSc )
{
var formals = formalsRaw . asSyndicateStructureArguments ;
var label = maybeLabel . numChildren === 1
? maybeLabel . children [ 0 ] . interval . contents
: JSON . stringify ( typeName . interval . contents ) ;
2016-05-10 04:44:02 +00:00
return 'var ' + typeName . asES5 + ' = Syndicate.Struct.makeConstructor(' +
2016-05-08 15:34:45 +00:00
label + ', ' + JSON . stringify ( formals ) + ');' ;
2016-04-06 16:22:30 +00:00
} ,
2016-08-08 02:03:35 +00:00
FieldDeclarationStatement : function ( _field , memberExpr , _eq , maybeInitExpr , sc ) {
2016-08-07 19:41:10 +00:00
return 'Syndicate.Actor.declareField(' + memberExpr . memberObjectExpr . asES5 + ', ' +
2016-08-08 02:03:35 +00:00
memberExpr . memberPropExpr . asES5 + ', ' +
( maybeInitExpr . numChildren === 1 ? maybeInitExpr . asES5 : 'undefined' ) +
')' +
2016-08-07 19:41:10 +00:00
sc . interval . contents ;
} ,
MemberExpression _fieldRefExp : function ( _field , memberExpr ) {
return 'Syndicate.Actor.referenceField(' + memberExpr . memberObjectExpr . asES5 + ', ' +
memberExpr . memberPropExpr . asES5 + ')' ;
} ,
UnaryExpression _fieldDelExp : function ( _delete , _field , memberExpr ) {
return 'Syndicate.Actor.deleteField(' + memberExpr . memberObjectExpr . asES5 + ', ' +
memberExpr . memberPropExpr . asES5 + ')' ;
} ,
2016-04-06 16:22:30 +00:00
SendMessageStatement : function ( _colons , expr , sc ) {
2016-04-07 07:44:34 +00:00
return 'Syndicate.Dataspace.send(' + expr . asES5 + ')' + sc . interval . contents ;
2016-04-06 16:22:30 +00:00
} ,
2016-08-25 12:13:44 +00:00
ActorEndpointStatement _start : function ( _on , _start , block ) {
return 'Syndicate.Actor.Facet.current.addInitBlock((function() ' + block . asES5 + '));' ;
2016-04-06 16:22:30 +00:00
} ,
2016-08-25 12:13:44 +00:00
ActorEndpointStatement _stop : function ( _on , _stop , block ) {
return 'Syndicate.Actor.Facet.current.addDoneBlock((function() ' + block . asES5 + '));' ;
2016-04-06 16:22:30 +00:00
} ,
2016-08-25 12:13:44 +00:00
ActorEndpointStatement _assert : function ( _assert , expr , whenClause , _sc ) {
return 'Syndicate.Actor.Facet.current.addAssertion(' +
buildSubscription ( [ expr ] , 'assert' , 'pattern' , whenClause , null ) + ');' ;
2016-04-06 16:22:30 +00:00
} ,
2016-08-25 12:13:44 +00:00
ActorEndpointStatement _event : function ( _on , eventPattern , block ) {
2016-04-06 16:22:30 +00:00
return buildOnEvent ( false ,
eventPattern . eventType ,
eventPattern . subscription ,
eventPattern . projection ,
eventPattern . bindings ,
block . asES5 ) ;
} ,
2016-08-25 12:13:44 +00:00
ActorEndpointStatement _onEvent : function ( _on , _event , id , block ) {
return 'Syndicate.Actor.Facet.current.addOnEventHandler((function(' + id . asES5 + ') ' +
block . asES5 + '));' ;
2016-05-15 20:20:50 +00:00
} ,
2016-08-25 12:13:44 +00:00
ActorEndpointStatement _stopOnWithCont : function ( _stop , _on , eventPattern , block ) {
return buildCaseEvent ( eventPattern , block . asES5 ) ;
} ,
ActorEndpointStatement _stopOnNoCont : function ( _stop , _on , eventPattern , _sc ) {
return buildCaseEvent ( eventPattern , '{}' ) ;
2016-08-07 19:41:10 +00:00
} ,
2016-08-25 12:13:44 +00:00
ActorEndpointStatement _dataflow : function ( _dataflow , block ) {
return 'Syndicate.Actor.Facet.current.addDataflow((function () ' + block . asES5 + '));' ;
} ,
ActorEndpointStatement _during : function ( _during , pattern , block ) {
2016-06-11 11:04:45 +00:00
var cachedAssertionVar = gensym ( 'cachedAssertion' ) ;
2016-04-06 16:22:30 +00:00
return buildOnEvent ( false ,
'asserted' ,
pattern . subscription ,
pattern . projection ,
pattern . bindings ,
2016-08-25 12:13:44 +00:00
'{\n' +
'var ' + cachedAssertionVar + ' = ' + pattern . instantiatedAssertion + ';\n' +
reactWrap ( block . asES5 + '\n' +
buildOnEvent ( true ,
'retracted' ,
pattern . instantiatedSubscription ( cachedAssertionVar ) ,
pattern . instantiatedProjection ( cachedAssertionVar ) ,
[ ] ,
'{}' ) ) + '}' ) ;
2016-04-06 16:22:30 +00:00
} ,
2017-02-20 22:19:56 +00:00
ActorEndpointStatement _duringSpawn : function ( _during , pattern , _spawn , _named , nameExpOpt , block )
2016-08-25 12:13:44 +00:00
{
2016-08-07 19:41:10 +00:00
var cachedAssertionVar = gensym ( 'cachedAssertion' ) ;
var actorBlock = {
2016-08-25 12:13:44 +00:00
asES5 : reactWrap ( block . asES5 + '\n' +
buildOnEvent ( true ,
'retracted' ,
pattern . instantiatedSubscription ( cachedAssertionVar ) ,
pattern . instantiatedProjection ( cachedAssertionVar ) ,
[ ] ,
'{}' ) )
2016-08-07 19:41:10 +00:00
} ;
return buildOnEvent ( false ,
'asserted' ,
pattern . subscription ,
pattern . projection ,
pattern . bindings ,
2016-08-25 12:13:44 +00:00
'{ var ' + cachedAssertionVar + ' = ' + pattern . instantiatedAssertion + ';\n' +
buildActor ( nameExpOpt , actorBlock , true ) + ' }' ) ;
2016-08-07 19:41:10 +00:00
} ,
2016-04-06 16:22:30 +00:00
2016-05-08 16:26:20 +00:00
AssertWhenClause : function ( _when , _lparen , expr , _rparen ) {
return expr . asES5 ;
2016-04-06 16:22:30 +00:00
}
} ;
semantics . extendAttribute ( 'modifiedSource' , modifiedSourceActions ) ;
2016-08-07 19:41:10 +00:00
semantics . addAttribute ( 'memberObjectExpr' , {
MemberExpression _propRefExp : function ( objExpr , _dot , id ) {
return objExpr ;
} ,
MemberExpression _arrayRefExp : function ( objExpr , _lbrack , propExpr , _rbrack ) {
return objExpr ;
}
} ) ;
semantics . addAttribute ( 'memberPropExpr' , {
MemberExpression _propRefExp : function ( objExpr , _dot , id ) {
return { asES5 : JSON . stringify ( id . interval . contents ) } ;
} ,
MemberExpression _arrayRefExp : function ( objExpr , _lbrack , propExpr , _rbrack ) {
return propExpr ;
}
} ) ;
2016-08-25 12:13:44 +00:00
///////////////////////////////////////////////////////////////////////////
2016-06-05 20:44:17 +00:00
2016-04-06 16:22:30 +00:00
semantics . addAttribute ( 'asSyndicateStructureArguments' , {
FormalParameterList : function ( formals ) {
return formals . asIteration ( ) . asSyndicateStructureArguments ;
} ,
identifier : function ( _name ) {
return this . interval . contents ;
}
} ) ;
semantics . addAttribute ( 'eventType' , {
FacetEventPattern _messageEvent : function ( _kw , _pattern ) { return 'message' ; } ,
FacetEventPattern _assertedEvent : function ( _kw , _pattern ) { return 'asserted' ; } ,
FacetEventPattern _retractedEvent : function ( _kw , _pattern ) { return 'retracted' ; } ,
FacetTransitionEventPattern _facetEvent : function ( pattern ) { return pattern . eventType ; } ,
FacetTransitionEventPattern _risingEdge : function ( _lp , expr , _rp ) { return 'risingEdge' ; }
} ) ;
2016-06-11 11:04:45 +00:00
function buildSubscription ( children , patchMethod , mode , whenClause , cachedAssertionVar ) {
2016-04-06 16:22:30 +00:00
var fragments = [ ] ;
2016-05-08 16:26:20 +00:00
var hasWhenClause = ( whenClause && ( whenClause . numChildren === 1 ) ) ;
2016-04-06 16:22:30 +00:00
fragments . push ( '(function() { var _ = Syndicate.__; return ' ) ;
2016-05-08 16:26:20 +00:00
if ( hasWhenClause ) {
fragments . push ( '(' + whenClause . asES5 + ') ? ' ) ;
}
2016-04-06 16:22:30 +00:00
if ( patchMethod ) {
fragments . push ( 'Syndicate.Patch.' + patchMethod + '(' ) ;
} else {
fragments . push ( '{ assertion: ' ) ;
}
2016-06-11 11:04:45 +00:00
if ( cachedAssertionVar ) {
fragments . push ( cachedAssertionVar ) ;
} else {
2016-07-11 16:06:07 +00:00
children . forEach ( function ( c ) { fragments . push ( c . buildSubscription ( mode ) ) ; } ) ;
2016-06-11 11:04:45 +00:00
}
2016-04-06 16:22:30 +00:00
if ( patchMethod ) {
fragments . push ( ', ' ) ;
} else {
fragments . push ( ', metalevel: ' ) ;
}
children . forEach ( function ( c ) { fragments . push ( c . metalevel ) } ) ;
if ( patchMethod ) {
fragments . push ( ')' ) ;
} else {
fragments . push ( ' }' ) ;
}
2016-05-08 16:26:20 +00:00
if ( hasWhenClause ) {
fragments . push ( ' : Syndicate.Patch.emptyPatch' ) ;
}
2016-04-06 16:22:30 +00:00
fragments . push ( '; })' ) ;
return fragments . join ( '' ) ;
}
semantics . addAttribute ( 'subscription' , {
_default : function ( children ) {
2016-06-11 11:04:45 +00:00
return buildSubscription ( children , 'sub' , 'pattern' , null , null ) ;
}
} ) ;
semantics . addAttribute ( 'instantiatedAssertion' , {
_default : function ( children ) {
var fragments = [ ] ;
fragments . push ( '(function() { var _ = Syndicate.__; return ' ) ;
2016-07-11 16:06:07 +00:00
children . forEach ( function ( c ) { fragments . push ( c . buildSubscription ( 'instantiated' ) ) ; } ) ;
2016-08-07 19:41:10 +00:00
fragments . push ( '; }).call(this)' ) ;
2016-06-11 11:04:45 +00:00
return fragments . join ( '' ) ;
2016-04-06 16:22:30 +00:00
}
} ) ;
2016-06-11 11:04:45 +00:00
semantics . addOperation ( 'instantiatedSubscription(cachedAssertionVar)' , {
2016-04-06 16:22:30 +00:00
_default : function ( children ) {
2016-06-11 11:04:45 +00:00
return buildSubscription ( children , 'sub' , 'instantiated' , null , this . args . cachedAssertionVar ) ;
2016-04-06 16:22:30 +00:00
}
} ) ;
2016-06-11 11:04:45 +00:00
semantics . addOperation ( 'instantiatedProjection(cachedAssertionVar)' , {
2016-04-06 16:22:30 +00:00
_default : function ( children ) {
2016-06-11 11:04:45 +00:00
return buildSubscription ( children , null , 'instantiated' , null , this . args . cachedAssertionVar ) ;
2016-04-06 16:22:30 +00:00
}
} ) ;
semantics . addAttribute ( 'projection' , {
_default : function ( children ) {
2016-06-11 11:04:45 +00:00
return buildSubscription ( children , null , 'projection' , null , null ) ;
2016-04-06 16:22:30 +00:00
}
} ) ;
semantics . addAttribute ( 'metalevel' , {
FacetEventPattern _messageEvent : function ( _kw , p ) { return p . metalevel ; } ,
FacetEventPattern _assertedEvent : function ( _kw , p ) { return p . metalevel ; } ,
FacetEventPattern _retractedEvent : function ( _kw , p ) { return p . metalevel ; } ,
FacetTransitionEventPattern _facetEvent : function ( pattern ) { return pattern . metalevel ; } ,
FacetPattern _withMetalevel : function ( _expr , _kw , metalevel ) {
return metalevel . interval . contents ;
} ,
FacetPattern _noMetalevel : function ( _expr ) {
return 0 ;
}
} ) ;
2016-07-11 16:06:07 +00:00
semantics . addOperation ( 'buildSubscription(mode)' , {
2016-04-06 16:22:30 +00:00
FacetEventPattern _messageEvent : function ( _kw , pattern ) {
2016-07-11 16:06:07 +00:00
return pattern . buildSubscription ( this . args . mode ) ;
2016-04-06 16:22:30 +00:00
} ,
FacetEventPattern _assertedEvent : function ( _kw , pattern ) {
2016-07-11 16:06:07 +00:00
return pattern . buildSubscription ( this . args . mode ) ;
2016-04-06 16:22:30 +00:00
} ,
FacetEventPattern _retractedEvent : function ( _kw , pattern ) {
2016-07-11 16:06:07 +00:00
return pattern . buildSubscription ( this . args . mode ) ;
2016-04-06 16:22:30 +00:00
} ,
FacetTransitionEventPattern _facetEvent : function ( pattern ) {
2016-07-11 16:06:07 +00:00
return pattern . buildSubscription ( this . args . mode ) ;
2016-04-06 16:22:30 +00:00
} ,
FacetPattern : function ( v ) {
2016-07-11 16:06:07 +00:00
return v . children [ 0 ] . buildSubscription ( this . args . mode ) ; // both branches!
2016-04-06 16:22:30 +00:00
} ,
2016-05-10 04:44:02 +00:00
AssignmentExpression _assignment : function ( lhsExpr , _assignmentOperator , rhsExpr ) {
var i = lhsExpr . interval . contents ;
if ( i [ 0 ] === '$' && i . length > 1 ) {
switch ( this . args . mode ) {
2016-07-11 16:06:07 +00:00
case 'pattern' : return rhsExpr . buildSubscription ( this . args . mode ) ;
case 'instantiated' : return lhsExpr . buildSubscription ( this . args . mode ) ;
case 'projection' :
return '(Syndicate._$(' + JSON . stringify ( i . slice ( 1 ) ) + ',' +
rhsExpr . buildSubscription ( this . args . mode ) +
'))' ;
2016-05-10 04:44:02 +00:00
default : throw new Error ( 'Unexpected buildSubscription mode ' + this . args . mode ) ;
}
} else {
2016-07-11 16:06:07 +00:00
return lhsExpr . buildSubscription ( this . args . mode ) +
_assignmentOperator . buildSubscription ( this . args . mode ) +
rhsExpr . buildSubscription ( this . args . mode ) ;
2016-05-10 04:44:02 +00:00
}
} ,
2016-08-07 19:41:10 +00:00
MemberExpression _fieldRefExp : function ( _field , memberExpr ) {
return 'Syndicate.Actor.referenceField(' +
memberExpr . memberObjectExpr . buildSubscription ( this . args . mode ) + ', ' +
memberExpr . memberPropExpr . buildSubscription ( this . args . mode ) + ')' ;
} ,
2016-04-06 16:22:30 +00:00
identifier : function ( _name ) {
var i = this . interval . contents ;
2016-05-10 04:44:02 +00:00
if ( i [ 0 ] === '$' && i . length > 1 ) {
2016-04-06 16:22:30 +00:00
switch ( this . args . mode ) {
2016-07-11 16:06:07 +00:00
case 'pattern' : return '_' ;
case 'instantiated' : return i . slice ( 1 ) ;
case 'projection' : return '(Syndicate._$(' + JSON . stringify ( i . slice ( 1 ) ) + '))' ;
2016-05-10 04:44:02 +00:00
default : throw new Error ( 'Unexpected buildSubscription mode ' + this . args . mode ) ;
2016-04-06 16:22:30 +00:00
}
} else {
2016-07-11 16:06:07 +00:00
return i ;
2016-04-06 16:22:30 +00:00
}
} ,
_terminal : function ( ) {
2016-07-11 16:06:07 +00:00
return undefined ;
2016-04-06 16:22:30 +00:00
} ,
_nonterminal : function ( children ) {
var self = this ;
2016-07-11 16:06:07 +00:00
return ES5 . translateNonterminalCode ( children ,
function ( n ) {
return n . buildSubscription ( self . args . mode ) ;
2016-08-01 20:46:13 +00:00
} ) || this . interval . contents ;
2016-04-06 16:22:30 +00:00
}
} ) ;
semantics . addAttribute ( 'bindings' , {
_default : function ( children ) {
var result = [ ] ;
this . pushBindings ( result ) ;
return result ;
}
} ) ;
semantics . addOperation ( 'pushBindings(accumulator)' , {
identifier : function ( _name ) {
var i = this . interval . contents ;
2016-05-10 04:44:02 +00:00
if ( i [ 0 ] === '$' && i . length > 1 ) {
2016-04-06 16:22:30 +00:00
this . args . accumulator . push ( i . slice ( 1 ) ) ;
}
} ,
_terminal : function ( ) { } ,
_nonterminal : function ( children ) {
var self = this ;
children . forEach ( function ( c ) { c . pushBindings ( self . args . accumulator ) ; } ) ;
}
} )
function compileSyndicateSource ( inputSource , onError ) {
var parseResult = grammar . match ( inputSource ) ;
if ( parseResult . failed ( ) ) {
if ( onError ) {
return onError ( parseResult . message , parseResult ) ;
} else {
console . error ( parseResult . message ) ;
return false ;
}
} else {
return '"use strict";\n' + semantics ( parseResult ) . asES5 ;
}
}
//---------------------------------------------------------------------------
module . exports . grammar = grammar ;
module . exports . semantics = semantics ;
module . exports . compileSyndicateSource = compileSyndicateSource ;
} ) . call ( this , require ( "buffer" ) . Buffer )
} , { "./es5.js" : 2 , "buffer" : 4 , "ohm-js" : 50 , "path" : 8 } ] , 2 : [ function ( require , module , exports ) {
( function ( Buffer ) {
//===========================================================================
// Copy of ohm-js/examples/ecmascript/es5.js to get browserify+brfs to work
//===========================================================================
/* eslint-env node */
'use strict' ;
// --------------------------------------------------------------------
// Imports
// --------------------------------------------------------------------
var path = require ( 'path' ) ;
var ohm = require ( 'ohm-js' ) ;
// --------------------------------------------------------------------
// Helpers
// --------------------------------------------------------------------
function isUndefined ( x ) { return x === void 0 ; }
// Take an Array of nodes, and whenever an _iter node is encountered, splice in its
// recursively-flattened children instead.
function flattenIterNodes ( nodes ) {
var result = [ ] ;
for ( var i = 0 ; i < nodes . length ; ++ i ) {
if ( nodes [ i ] . _node . ctorName === '_iter' ) {
result . push . apply ( result , flattenIterNodes ( nodes [ i ] . children ) ) ;
} else {
result . push ( nodes [ i ] ) ;
}
}
return result ;
}
// Comparison function for sorting nodes based on their interval's start index.
function compareByInterval ( node , otherNode ) {
return node . interval . startIdx - otherNode . interval . startIdx ;
}
2016-07-11 16:06:07 +00:00
function translateNonterminalCode ( children , nodeTranslator ) {
var flatChildren = flattenIterNodes ( children ) . sort ( compareByInterval ) ;
var childResults = flatChildren . map ( nodeTranslator ) ;
if ( flatChildren . length === 0 || childResults . every ( isUndefined ) ) {
return undefined ;
}
var code = '' ;
var interval = flatChildren [ 0 ] . interval . collapsedLeft ( ) ;
for ( var i = 0 ; i < flatChildren . length ; ++ i ) {
if ( childResults [ i ] == null ) {
// Grow the interval to include this node.
interval = interval . coverageWith ( flatChildren [ i ] . interval . collapsedRight ( ) ) ;
} else {
interval = interval . coverageWith ( flatChildren [ i ] . interval . collapsedLeft ( ) ) ;
code += interval . contents + childResults [ i ] ;
interval = flatChildren [ i ] . interval . collapsedRight ( ) ;
}
}
code += interval . contents ;
return code ;
}
2016-04-06 16:22:30 +00:00
// Semantic actions for the `modifiedSource` attribute (see below).
var modifiedSourceActions = {
_nonterminal : function ( children ) {
2016-07-11 16:06:07 +00:00
return translateNonterminalCode ( children ,
2016-08-01 20:46:13 +00:00
function ( n ) { return n . modifiedSource ; } )
|| this . interval . contents ;
2016-04-06 16:22:30 +00:00
} ,
_iter : function ( _ ) {
throw new Error ( '_iter semantic action should never be hit' ) ;
} ,
_terminal : function ( ) {
return undefined ;
}
} ;
// Instantiate the ES5 grammar.
2016-06-05 20:44:17 +00:00
var contents = Buffer ( " LyoKICBUaGlzIGdyYW1tYXIgd2FzIG9yaWdpbmFsbHkgYmFzZWQgb24gVG9tIFZhbiBDdXRzZW0ncyBFUzUgcGFyc2VyIGZyb20gdGhlCiAgZXMtbGFiIHByb2plY3QgKGh0dHBzOi8vZ2l0aHViLmNvbS90dmN1dHNlbS9lcy1sYWIvYmxvYi9tYXN0ZXIvc3JjL3BhcnNlci9lczVwYXJzZXIub2pzKSwKICBhbmQgd2FzIGFkYXB0ZWQgdG8gT2htIGJ5IFRvbnkgR2Fybm9jay1Kb25lcyA8dG9ueWdhcm5vY2tqb25lc0BnbWFpbC5jb20 + IGluIDIwMTQuCgogIFRoZSBvcmlnaW5hbCBjb3B5cmlnaHQgYW5kIGxpY2Vuc2UgZm9sbG93czoKKi8KCi8vIENvcHlyaWdodCAoQykgMjAwOSBHb29nbGUgSW5jLgovLwovLyBMaWNlbnNlZCB1bmRlciB0aGUgQXBhY2hlIExpY2Vuc2UsIFZlcnNpb24gMi4wICh0aGUgIkxpY2Vuc2UiKTsKLy8geW91IG1heSBub3QgdXNlIHRoaXMgZmlsZSBleGNlcHQgaW4gY29tcGxpYW5jZSB3aXRoIHRoZSBMaWNlbnNlLgovLyBZb3UgbWF5IG9idGFpbiBhIGNvcHkgb2YgdGhlIExpY2Vuc2UgYXQKLy8KLy8gaHR0cDovL3d3dy5hcGFjaGUub3JnL2xpY2Vuc2VzL0xJQ0VOU0UtMi4wCi8vCi8vIFVubGVzcyByZXF1aXJlZCBieSBhcHBsaWNhYmxlIGxhdyBvciBhZ3JlZWQgdG8gaW4gd3JpdGluZywgc29mdHdhcmUKLy8gZGlzdHJpYnV0ZWQgdW5kZXIgdGhlIExpY2Vuc2UgaXMgZGlzdHJpYnV0ZWQgb24gYW4gIkFTIElTIiBCQVNJUywKLy8gV0lUSE9VVCBXQVJSQU5USUVTIE9SIENPTkRJVElPTlMgT0YgQU5ZIEtJTkQsIGVpdGhlciBleHByZXNzIG9yIGltcGxpZWQuCi8vIFNlZSB0aGUgTGljZW5zZSBmb3IgdGhlIHNwZWNpZmljIGxhbmd1YWdlIGdvdmVybmluZyBwZXJtaXNzaW9ucyBhbmQKLy8gbGltaXRhdGlvbnMgdW5kZXIgdGhlIExpY2Vuc2UuCgovKiAoZW5kIG9mIG9yaWdpbmFsIGNvcHlyaWdodCBhbmQgbGljZW5zZSkgKi8KCkVTNSB7CgogIFByb2dyYW0gPSBEaXJlY3RpdmUqIFNvdXJjZUVsZW1lbnQqCgogIC8vIMKnQS4xIExleGljYWwgR3JhbW1hciAtLSBodHRwOi8vZWNtYS1pbnRlcm5hdGlvbmFsLm9yZy9lY21hLTI2Mi81LjEvI3NlYy1BLjEKCiAgLyoKICAgIE5vdGU6IHRoZSBmb2xsb3dpbmcgbGV4aWNhbCBjb252ZW50aW9ucyAoc2VlIGh0dHA6Ly9lY21hLWludGVybmF0aW9uYWwub3JnL2VjbWEtMjYyLzUuMS8jc2VjLTcpCiAgICBhcmUgbm90IGltcGxlbWVudGVkIGluIHRoaXMgcGFyc2VyLgoKICAgIC8vIEdvYWwgcHJvZHVjdGlvbiBpbiBjb250ZXh0cyB3aGVyZSBhIGxlYWRpbmcgIi8iIG9yICIvPSIgaXMgcGVybWl0dGVkOgogICAgSW5wdXRFbGVtZW50RGl2ID0gd2hpdGVzcGFjZSB8IGxpbmVUZXJtaW5hdG9yIHwgY29tbWVudCB8IHRva2VuIHwgRGl2UHVuY3R1YXRvcgoKICAgIC8vIEdvYWwgcHJvZHVjdGlvbiBpbiBjb250ZXh0cyB3aGVyZSBhIGxlYWRpbmcgIi8iIG9yICIvPScgaXMgbm90IHBlcm1pdHRlZDoKICAgIElucHV0RWxlbWVudFJlZ0V4cCA9IHdoaXRlc3BhY2UgfCBsaW5lVGVybWluYXRvciB8IGNvbW1lbnQgfCB0b2tlbiB8IHJlZ3VsYXJFeHByZXNzaW9uTGl0ZXJhbAogICovCgogIHNvdXJjZUNoYXJhY3RlciA9IGFueQoKICAvLyBPdmVycmlkZSBPaG0ncyBidWlsdC1pbiBkZWZpbml0aW9uIG9mIHNwYWNlLgogIHNwYWNlIDo9IHdoaXRlc3BhY2UgfCBsaW5lVGVybWluYXRvciB8IGNvbW1lbnQKCiAgd2hpdGVzcGFjZSA9ICJcdCIKICAgICAgICAgICAgIHwgIlx4MEIiICAgIC0tIHZlcnRpY2FsVGFiCiAgICAgICAgICAgICB8ICJceDBDIiAgICAtLSBmb3JtRmVlZAogICAgICAgICAgICAgfCAiICIKICAgICAgICAgICAgIHwgIlx1MDBBMCIgIC0tIG5vQnJlYWtTcGFjZQogICAgICAgICAgICAgfCAiXHVGRUZGIiAgLS0gYnl0ZU9yZGVyTWFyawogICAgICAgICAgICAgfCB1bmljb2RlU3BhY2VTZXBhcmF0b3IKCiAgbGluZVRlcm1pbmF0b3IgPSAiXG4iIHwgIlxyIiB8ICJcdTIwMjgiIHwgIlx1MjAyOSIKICBsaW5lVGVybWluYXRvclNlcXVlbmNlID0gIlxuIiB8ICJcciIgfiJcbiIgfCAiXHUyMDI4IiB8ICJcdTIwMjkiIHwgIlxyXG4iCgogIGNvbW1lbnQgPSBtdWx0aUxpbmVDb21tZW50IHwgc2luZ2xlTGluZUNvbW1lbnQKCiAgbXVsdGlMaW5lQ29tbWVudCA9ICIvKiIgKH4iKi8iIHNvdXJjZUNoYXJhY3RlcikqICIqLyIKICBzaW5nbGVMaW5lQ29tbWVudCA9ICIvLyIgKH5saW5lVGVybWluYXRvciBzb3VyY2VDaGFyYWN0ZXIpKgoKICBpZGVudGlmaWVyIChhbiBpZGVudGlmaWVyKSA9IH5yZXNlcnZlZFdvcmQgaWRlbnRpZmllck5hbWUKICBpZGVudGlmaWVyTmFtZSA9IGlkZW50aWZpZXJTdGFydCBpZGVudGlmaWVyUGFydCoKCiAgaWRlbnRpZmllclN0YXJ0ID0gbGV0dGVyIHwgIiQiIHwgIl8iCiAgICAgICAgICAgICAgICAgIHwgIlxcIiB1bmljb2RlRXNjYXBlU2VxdWVuY2UgLS0gZXNjYXBlZAogIGlkZW50aWZpZXJQYXJ0ID0gaWRlbnRpZmllclN0YXJ0IHwgdW5pY29kZUNvbWJpbmluZ01hcmsKICAgICAgICAgICAgICAgICB8IHVuaWNvZGVEaWdpdCB8IHVuaWNvZGVDb25uZWN0b3JQdW5jdHVhdGlvbgogICAgICAgICAgICAgICAgIHwgIlx1MjAwQyIgfCAiXHUyMDBEIgogbGV0dGVyICs9IHVuaWNvZGVDYXRlZ29yeU5sCiAgdW5pY29kZUNhdGVnb3J5TmwKICAgID0gIlx1MjE2MCIuLiJcdTIxODIiIHwgIlx1MzAwNyIgfCAiXHUzMDIxIi4uIlx1MzAyOSIKICB1bmljb2RlRGlnaXQgKGEgZGlnaXQpCiAgICA9ICJcdTAwMzAiLi4iXHUwMDM5IiB8ICJcdTA2NjAiLi4iXHUwNjY5IiB8ICJcdTA2RjAiLi4iXHUwNkY5IiB8ICJcdTA5NjYiLi4iXHUwOTZGIiB8ICJcdTA5RTYiLi4iXHUwOUVGIiB8ICJcdTBBNjYiLi4iXHUwQTZGIiB8ICJcdTBBRTYiLi4iXHUwQUVGIiB8ICJcdTBCNjYiLi4iXHUwQjZGIiB8ICJcdTBCRTciLi4iXHUwQkVGIiB8ICJcdTBDNjYiLi4iXHUwQzZGIiB8ICJcdTBDRTYiLi4iXHUwQ0VGIiB8ICJcdTBENjYiLi4iXHUwRDZGIiB8ICJcdTBFNTAiLi4iXHUwRTU5IiB8ICJcdTBFRDAiLi4iXHUwRUQ5IiB8ICJcdTBGMjAiLi4iXHUwRjI5IiB8ICJcdUZGMTAi
2016-04-06 16:22:30 +00:00
var g = ohm . grammars ( contents ) . ES5 ;
var semantics = g . semantics ( ) ;
// An attribute whose value is either a string representing the modified source code for the
// node, or undefined (which means that the original source code should be used).
semantics . addAttribute ( 'modifiedSource' , modifiedSourceActions ) ;
// A simple wrapper around the `modifiedSource` attribute, which always returns a string
// containing the ES5 source code for the node.
semantics . addAttribute ( 'asES5' , {
_nonterminal : function ( children ) {
return isUndefined ( this . modifiedSource ) ? this . interval . contents : this . modifiedSource ;
}
} ) ;
module . exports = {
grammar : g ,
2016-07-11 16:06:07 +00:00
semantics : semantics ,
translateNonterminalCode : translateNonterminalCode
2016-04-06 16:22:30 +00:00
} ;
} ) . call ( this , require ( "buffer" ) . Buffer )
} , { "buffer" : 4 , "ohm-js" : 50 , "path" : 8 } ] , 3 : [ function ( require , module , exports ) {
'use strict' ;
var compiler = require ( './compiler.js' ) ;
function getUrlContent ( url ) {
var req = new XMLHttpRequest ( ) ;
req . open ( 'GET' , url , false ) ;
try {
req . send ( ) ;
if ( req . status === 0 || req . status === 200 ) {
return req . responseText ;
}
} catch ( e ) {
console . error ( "Error while loading " + url , e ) ;
}
return false ;
}
function translateSyndicateScripts ( ) {
var scriptNodes = document . querySelectorAll ( 'script[type="text/syndicate-js"]' ) ;
var allSources = [ ] ;
for ( var i = 0 ; i < scriptNodes . length ; i ++ ) {
var n = scriptNodes [ i ] ;
var srcUrl = n . getAttribute ( 'src' ) ;
allSources . push ( srcUrl ? getUrlContent ( srcUrl ) : n . innerHTML ) ;
}
var allSourceText = allSources . join ( '\n;\n' ) ;
var output = compiler . compileSyndicateSource ( allSourceText ) ;
var f = new Function ( output ) ;
2016-06-11 11:04:45 +00:00
f . call ( window ) ;
2016-04-06 16:22:30 +00:00
}
document . addEventListener ( 'DOMContentLoaded' , translateSyndicateScripts , false ) ;
//---------------------------------------------------------------------------
module . exports = compiler ;
} , { "./compiler.js" : 1 } ] , 4 : [ function ( require , module , exports ) {
( function ( global ) {
/ * !
* The buffer module from node . js , for the browser .
*
* @ author Feross Aboukhadijeh < feross @ feross . org > < http : //feross.org>
* @ license MIT
* /
/* eslint-disable no-proto */
'use strict'
var base64 = require ( 'base64-js' )
var ieee754 = require ( 'ieee754' )
var isArray = require ( 'isarray' )
exports . Buffer = Buffer
exports . SlowBuffer = SlowBuffer
exports . INSPECT _MAX _BYTES = 50
/ * *
* If ` Buffer.TYPED_ARRAY_SUPPORT ` :
* === true Use Uint8Array implementation ( fastest )
* === false Use Object implementation ( most compatible , even IE6 )
*
* Browsers that support typed arrays are IE 10 + , Firefox 4 + , Chrome 7 + , Safari 5.1 + ,
* Opera 11.6 + , iOS 4.2 + .
*
* Due to various browser bugs , sometimes the Object implementation will be used even
* when the browser supports typed arrays .
*
* Note :
*
* - Firefox 4 - 29 lacks support for adding new properties to ` Uint8Array ` instances ,
* See : https : //bugzilla.mozilla.org/show_bug.cgi?id=695438.
*
* - Chrome 9 - 10 is missing the ` TypedArray.prototype.subarray ` function .
*
* - IE10 has a broken ` TypedArray.prototype.subarray ` function which returns arrays of
* incorrect length in some situations .
* We detect these buggy browsers and set ` Buffer.TYPED_ARRAY_SUPPORT ` to ` false ` so they
* get the Object implementation , which is slower but behaves correctly .
* /
Buffer . TYPED _ARRAY _SUPPORT = global . TYPED _ARRAY _SUPPORT !== undefined
? global . TYPED _ARRAY _SUPPORT
: typedArraySupport ( )
2016-05-02 21:15:05 +00:00
/ *
* Export kMaxLength after typed array support is determined .
* /
exports . kMaxLength = kMaxLength ( )
2016-04-06 16:22:30 +00:00
function typedArraySupport ( ) {
try {
var arr = new Uint8Array ( 1 )
2017-02-20 22:19:56 +00:00
arr . _ _proto _ _ = { _ _proto _ _ : Uint8Array . prototype , foo : function ( ) { return 42 } }
2016-04-06 16:22:30 +00:00
return arr . foo ( ) === 42 && // typed array instances can be augmented
typeof arr . subarray === 'function' && // chrome 9-10 lack `subarray`
arr . subarray ( 1 , 1 ) . byteLength === 0 // ie10 has broken `subarray`
} catch ( e ) {
return false
}
}
function kMaxLength ( ) {
return Buffer . TYPED _ARRAY _SUPPORT
? 0x7fffffff
: 0x3fffffff
}
2016-05-02 21:15:05 +00:00
function createBuffer ( that , length ) {
if ( kMaxLength ( ) < length ) {
throw new RangeError ( 'Invalid typed array length' )
}
if ( Buffer . TYPED _ARRAY _SUPPORT ) {
// Return an augmented `Uint8Array` instance, for best performance
that = new Uint8Array ( length )
that . _ _proto _ _ = Buffer . prototype
} else {
// Fallback: Return an object instance of the Buffer class
if ( that === null ) {
that = new Buffer ( length )
}
that . length = length
}
return that
}
2016-04-06 16:22:30 +00:00
/ * *
* The Buffer constructor returns instances of ` Uint8Array ` that have their
* prototype changed to ` Buffer.prototype ` . Furthermore , ` Buffer ` is a subclass of
* ` Uint8Array ` , so the returned instances will have all the node ` Buffer ` methods
* and the ` Uint8Array ` methods . Square bracket notation works as expected -- it
* returns a single octet .
*
* The ` Uint8Array ` prototype remains unmodified .
* /
2016-05-02 21:15:05 +00:00
function Buffer ( arg , encodingOrOffset , length ) {
if ( ! Buffer . TYPED _ARRAY _SUPPORT && ! ( this instanceof Buffer ) ) {
return new Buffer ( arg , encodingOrOffset , length )
2016-04-06 16:22:30 +00:00
}
// Common case.
if ( typeof arg === 'number' ) {
2016-05-02 21:15:05 +00:00
if ( typeof encodingOrOffset === 'string' ) {
throw new Error (
'If encoding is specified then the first argument must be a string'
)
}
return allocUnsafe ( this , arg )
2016-04-06 16:22:30 +00:00
}
2016-05-02 21:15:05 +00:00
return from ( this , arg , encodingOrOffset , length )
2016-04-06 16:22:30 +00:00
}
2016-05-02 21:15:05 +00:00
Buffer . poolSize = 8192 // not used by this implementation
2016-04-06 16:22:30 +00:00
// TODO: Legacy, not needed anymore. Remove in next major version.
Buffer . _augment = function ( arr ) {
arr . _ _proto _ _ = Buffer . prototype
return arr
}
2016-05-02 21:15:05 +00:00
function from ( that , value , encodingOrOffset , length ) {
if ( typeof value === 'number' ) {
throw new TypeError ( '"value" argument must not be a number' )
2016-04-06 16:22:30 +00:00
}
2016-05-02 21:15:05 +00:00
if ( typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer ) {
return fromArrayBuffer ( that , value , encodingOrOffset , length )
}
2016-04-06 16:22:30 +00:00
2016-05-02 21:15:05 +00:00
if ( typeof value === 'string' ) {
return fromString ( that , value , encodingOrOffset )
}
2016-04-06 16:22:30 +00:00
2016-05-02 21:15:05 +00:00
return fromObject ( that , value )
2016-04-06 16:22:30 +00:00
}
2016-05-02 21:15:05 +00:00
/ * *
* Functionally equivalent to Buffer ( arg , encoding ) but throws a TypeError
* if value is a number .
* Buffer . from ( str [ , encoding ] )
* Buffer . from ( array )
* Buffer . from ( buffer )
* Buffer . from ( arrayBuffer [ , byteOffset [ , length ] ] )
* * /
Buffer . from = function ( value , encodingOrOffset , length ) {
return from ( null , value , encodingOrOffset , length )
}
2016-04-06 16:22:30 +00:00
2016-05-02 21:15:05 +00:00
if ( Buffer . TYPED _ARRAY _SUPPORT ) {
Buffer . prototype . _ _proto _ _ = Uint8Array . prototype
Buffer . _ _proto _ _ = Uint8Array
if ( typeof Symbol !== 'undefined' && Symbol . species &&
Buffer [ Symbol . species ] === Buffer ) {
// Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97
Object . defineProperty ( Buffer , Symbol . species , {
value : null ,
configurable : true
} )
2016-04-06 16:22:30 +00:00
}
2016-05-02 21:15:05 +00:00
}
2016-04-06 16:22:30 +00:00
2016-05-02 21:15:05 +00:00
function assertSize ( size ) {
if ( typeof size !== 'number' ) {
throw new TypeError ( '"size" argument must be a number' )
2017-02-20 22:19:56 +00:00
} else if ( size < 0 ) {
throw new RangeError ( '"size" argument must not be negative' )
2016-04-06 16:22:30 +00:00
}
2016-05-02 21:15:05 +00:00
}
2016-04-06 16:22:30 +00:00
2016-05-02 21:15:05 +00:00
function alloc ( that , size , fill , encoding ) {
assertSize ( size )
if ( size <= 0 ) {
return createBuffer ( that , size )
}
if ( fill !== undefined ) {
// Only pay attention to encoding if it's a string. This
// prevents accidentally sending in a number that would
// be interpretted as a start offset.
return typeof encoding === 'string'
? createBuffer ( that , size ) . fill ( fill , encoding )
: createBuffer ( that , size ) . fill ( fill )
}
return createBuffer ( that , size )
2016-04-06 16:22:30 +00:00
}
2016-05-02 21:15:05 +00:00
/ * *
* Creates a new filled Buffer instance .
* alloc ( size [ , fill [ , encoding ] ] )
* * /
Buffer . alloc = function ( size , fill , encoding ) {
return alloc ( null , size , fill , encoding )
2016-04-06 16:22:30 +00:00
}
2016-05-02 21:15:05 +00:00
function allocUnsafe ( that , size ) {
assertSize ( size )
that = createBuffer ( that , size < 0 ? 0 : checked ( size ) | 0 )
if ( ! Buffer . TYPED _ARRAY _SUPPORT ) {
2017-02-20 22:19:56 +00:00
for ( var i = 0 ; i < size ; ++ i ) {
2016-05-02 21:15:05 +00:00
that [ i ] = 0
}
2016-04-06 16:22:30 +00:00
}
return that
}
2016-05-02 21:15:05 +00:00
/ * *
* Equivalent to Buffer ( num ) , by default creates a non - zero - filled Buffer instance .
* * /
Buffer . allocUnsafe = function ( size ) {
return allocUnsafe ( null , size )
}
/ * *
* Equivalent to SlowBuffer ( num ) , by default creates a non - zero - filled Buffer instance .
* /
Buffer . allocUnsafeSlow = function ( size ) {
return allocUnsafe ( null , size )
2016-04-06 16:22:30 +00:00
}
2016-05-02 21:15:05 +00:00
function fromString ( that , string , encoding ) {
if ( typeof encoding !== 'string' || encoding === '' ) {
encoding = 'utf8'
}
2016-04-06 16:22:30 +00:00
2016-05-02 21:15:05 +00:00
if ( ! Buffer . isEncoding ( encoding ) ) {
throw new TypeError ( '"encoding" must be a valid string encoding' )
2016-04-06 16:22:30 +00:00
}
2016-05-02 21:15:05 +00:00
var length = byteLength ( string , encoding ) | 0
that = createBuffer ( that , length )
2017-02-20 22:19:56 +00:00
var actual = that . write ( string , encoding )
if ( actual !== length ) {
// Writing a hex string, for example, that contains invalid characters will
// cause everything after the first invalid character to be ignored. (e.g.
// 'abxxcd' will be treated as 'ab')
that = that . slice ( 0 , actual )
}
2016-04-06 16:22:30 +00:00
return that
}
function fromArrayLike ( that , array ) {
2017-02-20 22:19:56 +00:00
var length = array . length < 0 ? 0 : checked ( array . length ) | 0
2016-05-02 21:15:05 +00:00
that = createBuffer ( that , length )
2016-04-06 16:22:30 +00:00
for ( var i = 0 ; i < length ; i += 1 ) {
that [ i ] = array [ i ] & 255
}
return that
}
2016-05-02 21:15:05 +00:00
function fromArrayBuffer ( that , array , byteOffset , length ) {
array . byteLength // this throws if `array` is not a valid ArrayBuffer
2016-04-06 16:22:30 +00:00
2016-05-02 21:15:05 +00:00
if ( byteOffset < 0 || array . byteLength < byteOffset ) {
throw new RangeError ( '\'offset\' is out of bounds' )
2016-04-06 16:22:30 +00:00
}
2016-05-02 21:15:05 +00:00
if ( array . byteLength < byteOffset + ( length || 0 ) ) {
throw new RangeError ( '\'length\' is out of bounds' )
2016-04-06 16:22:30 +00:00
}
2017-02-20 22:19:56 +00:00
if ( byteOffset === undefined && length === undefined ) {
array = new Uint8Array ( array )
} else if ( length === undefined ) {
2016-05-02 21:15:05 +00:00
array = new Uint8Array ( array , byteOffset )
} else {
array = new Uint8Array ( array , byteOffset , length )
}
2016-04-06 16:22:30 +00:00
if ( Buffer . TYPED _ARRAY _SUPPORT ) {
// Return an augmented `Uint8Array` instance, for best performance
2016-05-02 21:15:05 +00:00
that = array
2016-04-06 16:22:30 +00:00
that . _ _proto _ _ = Buffer . prototype
} else {
// Fallback: Return an object instance of the Buffer class
2016-05-02 21:15:05 +00:00
that = fromArrayLike ( that , array )
2016-04-06 16:22:30 +00:00
}
2016-05-02 21:15:05 +00:00
return that
}
2016-04-06 16:22:30 +00:00
2016-05-02 21:15:05 +00:00
function fromObject ( that , obj ) {
if ( Buffer . isBuffer ( obj ) ) {
var len = checked ( obj . length ) | 0
that = createBuffer ( that , len )
2016-04-06 16:22:30 +00:00
2016-05-02 21:15:05 +00:00
if ( that . length === 0 ) {
return that
}
obj . copy ( that , 0 , 0 , len )
return that
}
if ( obj ) {
if ( ( typeof ArrayBuffer !== 'undefined' &&
obj . buffer instanceof ArrayBuffer ) || 'length' in obj ) {
if ( typeof obj . length !== 'number' || isnan ( obj . length ) ) {
return createBuffer ( that , 0 )
}
return fromArrayLike ( that , obj )
}
if ( obj . type === 'Buffer' && isArray ( obj . data ) ) {
return fromArrayLike ( that , obj . data )
}
}
throw new TypeError ( 'First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.' )
2016-04-06 16:22:30 +00:00
}
function checked ( length ) {
2017-02-20 22:19:56 +00:00
// Note: cannot use `length < kMaxLength()` here because that fails when
2016-04-06 16:22:30 +00:00
// length is NaN (which is otherwise coerced to zero.)
if ( length >= kMaxLength ( ) ) {
throw new RangeError ( 'Attempt to allocate Buffer larger than maximum ' +
'size: 0x' + kMaxLength ( ) . toString ( 16 ) + ' bytes' )
}
return length | 0
}
2016-05-02 21:15:05 +00:00
function SlowBuffer ( length ) {
if ( + length != length ) { // eslint-disable-line eqeqeq
length = 0
}
return Buffer . alloc ( + length )
2016-04-06 16:22:30 +00:00
}
Buffer . isBuffer = function isBuffer ( b ) {
return ! ! ( b != null && b . _isBuffer )
}
Buffer . compare = function compare ( a , b ) {
if ( ! Buffer . isBuffer ( a ) || ! Buffer . isBuffer ( b ) ) {
throw new TypeError ( 'Arguments must be Buffers' )
}
if ( a === b ) return 0
var x = a . length
var y = b . length
2016-05-02 21:15:05 +00:00
for ( var i = 0 , len = Math . min ( x , y ) ; i < len ; ++ i ) {
if ( a [ i ] !== b [ i ] ) {
x = a [ i ]
y = b [ i ]
break
}
2016-04-06 16:22:30 +00:00
}
if ( x < y ) return - 1
if ( y < x ) return 1
return 0
}
Buffer . isEncoding = function isEncoding ( encoding ) {
switch ( String ( encoding ) . toLowerCase ( ) ) {
case 'hex' :
case 'utf8' :
case 'utf-8' :
case 'ascii' :
2017-02-20 22:19:56 +00:00
case 'latin1' :
2016-04-06 16:22:30 +00:00
case 'binary' :
case 'base64' :
case 'ucs2' :
case 'ucs-2' :
case 'utf16le' :
case 'utf-16le' :
return true
default :
return false
}
}
Buffer . concat = function concat ( list , length ) {
2016-05-02 21:15:05 +00:00
if ( ! isArray ( list ) ) {
throw new TypeError ( '"list" argument must be an Array of Buffers' )
}
2016-04-06 16:22:30 +00:00
if ( list . length === 0 ) {
2016-05-02 21:15:05 +00:00
return Buffer . alloc ( 0 )
2016-04-06 16:22:30 +00:00
}
var i
if ( length === undefined ) {
length = 0
2017-02-20 22:19:56 +00:00
for ( i = 0 ; i < list . length ; ++ i ) {
2016-04-06 16:22:30 +00:00
length += list [ i ] . length
}
}
2016-05-02 21:15:05 +00:00
var buffer = Buffer . allocUnsafe ( length )
2016-04-06 16:22:30 +00:00
var pos = 0
2017-02-20 22:19:56 +00:00
for ( i = 0 ; i < list . length ; ++ i ) {
2016-05-02 21:15:05 +00:00
var buf = list [ i ]
if ( ! Buffer . isBuffer ( buf ) ) {
throw new TypeError ( '"list" argument must be an Array of Buffers' )
}
buf . copy ( buffer , pos )
pos += buf . length
2016-04-06 16:22:30 +00:00
}
2016-05-02 21:15:05 +00:00
return buffer
2016-04-06 16:22:30 +00:00
}
function byteLength ( string , encoding ) {
2016-05-02 21:15:05 +00:00
if ( Buffer . isBuffer ( string ) ) {
return string . length
}
if ( typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer . isView === 'function' &&
( ArrayBuffer . isView ( string ) || string instanceof ArrayBuffer ) ) {
return string . byteLength
}
if ( typeof string !== 'string' ) {
string = '' + string
}
2016-04-06 16:22:30 +00:00
var len = string . length
if ( len === 0 ) return 0
// Use a for loop to avoid recursion
var loweredCase = false
for ( ; ; ) {
switch ( encoding ) {
case 'ascii' :
2017-02-20 22:19:56 +00:00
case 'latin1' :
2016-04-06 16:22:30 +00:00
case 'binary' :
return len
case 'utf8' :
case 'utf-8' :
2016-05-02 21:15:05 +00:00
case undefined :
2016-04-06 16:22:30 +00:00
return utf8ToBytes ( string ) . length
case 'ucs2' :
case 'ucs-2' :
case 'utf16le' :
case 'utf-16le' :
return len * 2
case 'hex' :
return len >>> 1
case 'base64' :
return base64ToBytes ( string ) . length
default :
if ( loweredCase ) return utf8ToBytes ( string ) . length // assume utf8
encoding = ( '' + encoding ) . toLowerCase ( )
loweredCase = true
}
}
}
Buffer . byteLength = byteLength
function slowToString ( encoding , start , end ) {
var loweredCase = false
2016-05-02 21:15:05 +00:00
// No need to verify that "this.length <= MAX_UINT32" since it's a read-only
// property of a typed array.
// This behaves neither like String nor Uint8Array in that we set start/end
// to their upper/lower bounds if the value passed is out of range.
// undefined is handled specially as per ECMA-262 6th Edition,
// Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
if ( start === undefined || start < 0 ) {
start = 0
}
// Return early if start > this.length. Done here to prevent potential uint32
// coercion fail below.
if ( start > this . length ) {
return ''
}
if ( end === undefined || end > this . length ) {
end = this . length
}
if ( end <= 0 ) {
return ''
}
// Force coersion to uint32. This will also coerce falsey/NaN values to 0.
end >>>= 0
start >>>= 0
if ( end <= start ) {
return ''
}
2016-04-06 16:22:30 +00:00
if ( ! encoding ) encoding = 'utf8'
while ( true ) {
switch ( encoding ) {
case 'hex' :
return hexSlice ( this , start , end )
case 'utf8' :
case 'utf-8' :
return utf8Slice ( this , start , end )
case 'ascii' :
return asciiSlice ( this , start , end )
2017-02-20 22:19:56 +00:00
case 'latin1' :
2016-04-06 16:22:30 +00:00
case 'binary' :
2017-02-20 22:19:56 +00:00
return latin1Slice ( this , start , end )
2016-04-06 16:22:30 +00:00
case 'base64' :
return base64Slice ( this , start , end )
case 'ucs2' :
case 'ucs-2' :
case 'utf16le' :
case 'utf-16le' :
return utf16leSlice ( this , start , end )
default :
if ( loweredCase ) throw new TypeError ( 'Unknown encoding: ' + encoding )
encoding = ( encoding + '' ) . toLowerCase ( )
loweredCase = true
}
}
}
// The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect
// Buffer instances.
Buffer . prototype . _isBuffer = true
2016-05-02 21:15:05 +00:00
function swap ( b , n , m ) {
var i = b [ n ]
b [ n ] = b [ m ]
b [ m ] = i
}
Buffer . prototype . swap16 = function swap16 ( ) {
var len = this . length
if ( len % 2 !== 0 ) {
throw new RangeError ( 'Buffer size must be a multiple of 16-bits' )
}
for ( var i = 0 ; i < len ; i += 2 ) {
swap ( this , i , i + 1 )
}
return this
}
Buffer . prototype . swap32 = function swap32 ( ) {
var len = this . length
if ( len % 4 !== 0 ) {
throw new RangeError ( 'Buffer size must be a multiple of 32-bits' )
}
for ( var i = 0 ; i < len ; i += 4 ) {
swap ( this , i , i + 3 )
swap ( this , i + 1 , i + 2 )
}
return this
}
2017-02-20 22:19:56 +00:00
Buffer . prototype . swap64 = function swap64 ( ) {
var len = this . length
if ( len % 8 !== 0 ) {
throw new RangeError ( 'Buffer size must be a multiple of 64-bits' )
}
for ( var i = 0 ; i < len ; i += 8 ) {
swap ( this , i , i + 7 )
swap ( this , i + 1 , i + 6 )
swap ( this , i + 2 , i + 5 )
swap ( this , i + 3 , i + 4 )
}
return this
}
2016-04-06 16:22:30 +00:00
Buffer . prototype . toString = function toString ( ) {
var length = this . length | 0
if ( length === 0 ) return ''
if ( arguments . length === 0 ) return utf8Slice ( this , 0 , length )
return slowToString . apply ( this , arguments )
}
Buffer . prototype . equals = function equals ( b ) {
if ( ! Buffer . isBuffer ( b ) ) throw new TypeError ( 'Argument must be a Buffer' )
if ( this === b ) return true
return Buffer . compare ( this , b ) === 0
}
Buffer . prototype . inspect = function inspect ( ) {
var str = ''
var max = exports . INSPECT _MAX _BYTES
if ( this . length > 0 ) {
str = this . toString ( 'hex' , 0 , max ) . match ( /.{2}/g ) . join ( ' ' )
if ( this . length > max ) str += ' ... '
}
return '<Buffer ' + str + '>'
}
2016-05-02 21:15:05 +00:00
Buffer . prototype . compare = function compare ( target , start , end , thisStart , thisEnd ) {
if ( ! Buffer . isBuffer ( target ) ) {
throw new TypeError ( 'Argument must be a Buffer' )
}
if ( start === undefined ) {
start = 0
}
if ( end === undefined ) {
end = target ? target . length : 0
}
if ( thisStart === undefined ) {
thisStart = 0
}
if ( thisEnd === undefined ) {
thisEnd = this . length
}
if ( start < 0 || end > target . length || thisStart < 0 || thisEnd > this . length ) {
throw new RangeError ( 'out of range index' )
}
if ( thisStart >= thisEnd && start >= end ) {
return 0
}
if ( thisStart >= thisEnd ) {
return - 1
}
if ( start >= end ) {
return 1
}
start >>>= 0
end >>>= 0
thisStart >>>= 0
thisEnd >>>= 0
if ( this === target ) return 0
var x = thisEnd - thisStart
var y = end - start
var len = Math . min ( x , y )
var thisCopy = this . slice ( thisStart , thisEnd )
var targetCopy = target . slice ( start , end )
for ( var i = 0 ; i < len ; ++ i ) {
if ( thisCopy [ i ] !== targetCopy [ i ] ) {
x = thisCopy [ i ]
y = targetCopy [ i ]
break
}
}
if ( x < y ) return - 1
if ( y < x ) return 1
return 0
2016-04-06 16:22:30 +00:00
}
2017-02-20 22:19:56 +00:00
// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
// OR the last index of `val` in `buffer` at offset <= `byteOffset`.
//
// Arguments:
// - buffer - a Buffer to search
// - val - a string, Buffer, or number
// - byteOffset - an index into `buffer`; will be clamped to an int32
// - encoding - an optional encoding, relevant is val is a string
// - dir - true for indexOf, false for lastIndexOf
function bidirectionalIndexOf ( buffer , val , byteOffset , encoding , dir ) {
// Empty buffer means no match
if ( buffer . length === 0 ) return - 1
// Normalize byteOffset
if ( typeof byteOffset === 'string' ) {
encoding = byteOffset
byteOffset = 0
} else if ( byteOffset > 0x7fffffff ) {
byteOffset = 0x7fffffff
} else if ( byteOffset < - 0x80000000 ) {
byteOffset = - 0x80000000
}
byteOffset = + byteOffset // Coerce to Number.
if ( isNaN ( byteOffset ) ) {
// byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
byteOffset = dir ? 0 : ( buffer . length - 1 )
}
// Normalize byteOffset: negative offsets start from the end of the buffer
if ( byteOffset < 0 ) byteOffset = buffer . length + byteOffset
if ( byteOffset >= buffer . length ) {
if ( dir ) return - 1
else byteOffset = buffer . length - 1
} else if ( byteOffset < 0 ) {
if ( dir ) byteOffset = 0
else return - 1
}
// Normalize val
if ( typeof val === 'string' ) {
val = Buffer . from ( val , encoding )
}
// Finally, search either indexOf (if dir is true) or lastIndexOf
if ( Buffer . isBuffer ( val ) ) {
// Special case: looking for empty string/buffer always fails
if ( val . length === 0 ) {
return - 1
}
return arrayIndexOf ( buffer , val , byteOffset , encoding , dir )
} else if ( typeof val === 'number' ) {
val = val & 0xFF // Search for a byte value [0-255]
if ( Buffer . TYPED _ARRAY _SUPPORT &&
typeof Uint8Array . prototype . indexOf === 'function' ) {
if ( dir ) {
return Uint8Array . prototype . indexOf . call ( buffer , val , byteOffset )
} else {
return Uint8Array . prototype . lastIndexOf . call ( buffer , val , byteOffset )
}
}
return arrayIndexOf ( buffer , [ val ] , byteOffset , encoding , dir )
}
throw new TypeError ( 'val must be string, number or Buffer' )
}
function arrayIndexOf ( arr , val , byteOffset , encoding , dir ) {
2016-05-02 21:15:05 +00:00
var indexSize = 1
var arrLength = arr . length
var valLength = val . length
if ( encoding !== undefined ) {
encoding = String ( encoding ) . toLowerCase ( )
if ( encoding === 'ucs2' || encoding === 'ucs-2' ||
encoding === 'utf16le' || encoding === 'utf-16le' ) {
if ( arr . length < 2 || val . length < 2 ) {
return - 1
}
indexSize = 2
arrLength /= 2
valLength /= 2
byteOffset /= 2
}
}
function read ( buf , i ) {
if ( indexSize === 1 ) {
return buf [ i ]
} else {
return buf . readUInt16BE ( i * indexSize )
}
}
2017-02-20 22:19:56 +00:00
var i
if ( dir ) {
var foundIndex = - 1
for ( i = byteOffset ; i < arrLength ; i ++ ) {
if ( read ( arr , i ) === read ( val , foundIndex === - 1 ? 0 : i - foundIndex ) ) {
if ( foundIndex === - 1 ) foundIndex = i
if ( i - foundIndex + 1 === valLength ) return foundIndex * indexSize
} else {
if ( foundIndex !== - 1 ) i -= i - foundIndex
foundIndex = - 1
}
2016-05-02 21:15:05 +00:00
}
2017-02-20 22:19:56 +00:00
} else {
if ( byteOffset + valLength > arrLength ) byteOffset = arrLength - valLength
for ( i = byteOffset ; i >= 0 ; i -- ) {
var found = true
for ( var j = 0 ; j < valLength ; j ++ ) {
if ( read ( arr , i + j ) !== read ( val , j ) ) {
found = false
break
}
}
if ( found ) return i
2016-04-06 16:22:30 +00:00
}
}
2017-02-20 22:19:56 +00:00
return - 1
2016-04-06 16:22:30 +00:00
}
2016-05-02 21:15:05 +00:00
Buffer . prototype . includes = function includes ( val , byteOffset , encoding ) {
return this . indexOf ( val , byteOffset , encoding ) !== - 1
}
2017-02-20 22:19:56 +00:00
Buffer . prototype . indexOf = function indexOf ( val , byteOffset , encoding ) {
return bidirectionalIndexOf ( this , val , byteOffset , encoding , true )
}
Buffer . prototype . lastIndexOf = function lastIndexOf ( val , byteOffset , encoding ) {
return bidirectionalIndexOf ( this , val , byteOffset , encoding , false )
}
2016-04-06 16:22:30 +00:00
function hexWrite ( buf , string , offset , length ) {
offset = Number ( offset ) || 0
var remaining = buf . length - offset
if ( ! length ) {
length = remaining
} else {
length = Number ( length )
if ( length > remaining ) {
length = remaining
}
}
// must be an even number of digits
var strLen = string . length
2017-02-20 22:19:56 +00:00
if ( strLen % 2 !== 0 ) throw new TypeError ( 'Invalid hex string' )
2016-04-06 16:22:30 +00:00
if ( length > strLen / 2 ) {
length = strLen / 2
}
2017-02-20 22:19:56 +00:00
for ( var i = 0 ; i < length ; ++ i ) {
2016-04-06 16:22:30 +00:00
var parsed = parseInt ( string . substr ( i * 2 , 2 ) , 16 )
2016-05-02 21:15:05 +00:00
if ( isNaN ( parsed ) ) return i
2016-04-06 16:22:30 +00:00
buf [ offset + i ] = parsed
}
return i
}
function utf8Write ( buf , string , offset , length ) {
return blitBuffer ( utf8ToBytes ( string , buf . length - offset ) , buf , offset , length )
}
function asciiWrite ( buf , string , offset , length ) {
return blitBuffer ( asciiToBytes ( string ) , buf , offset , length )
}
2017-02-20 22:19:56 +00:00
function latin1Write ( buf , string , offset , length ) {
2016-04-06 16:22:30 +00:00
return asciiWrite ( buf , string , offset , length )
}
function base64Write ( buf , string , offset , length ) {
return blitBuffer ( base64ToBytes ( string ) , buf , offset , length )
}
function ucs2Write ( buf , string , offset , length ) {
return blitBuffer ( utf16leToBytes ( string , buf . length - offset ) , buf , offset , length )
}
Buffer . prototype . write = function write ( string , offset , length , encoding ) {
// Buffer#write(string)
if ( offset === undefined ) {
encoding = 'utf8'
length = this . length
offset = 0
// Buffer#write(string, encoding)
} else if ( length === undefined && typeof offset === 'string' ) {
encoding = offset
length = this . length
offset = 0
// Buffer#write(string, offset[, length][, encoding])
} else if ( isFinite ( offset ) ) {
offset = offset | 0
if ( isFinite ( length ) ) {
length = length | 0
if ( encoding === undefined ) encoding = 'utf8'
} else {
encoding = length
length = undefined
}
// legacy write(string, encoding, offset, length) - remove in v0.13
} else {
2016-05-02 21:15:05 +00:00
throw new Error (
'Buffer.write(string, encoding, offset[, length]) is no longer supported'
)
2016-04-06 16:22:30 +00:00
}
var remaining = this . length - offset
if ( length === undefined || length > remaining ) length = remaining
if ( ( string . length > 0 && ( length < 0 || offset < 0 ) ) || offset > this . length ) {
2016-05-02 21:15:05 +00:00
throw new RangeError ( 'Attempt to write outside buffer bounds' )
2016-04-06 16:22:30 +00:00
}
if ( ! encoding ) encoding = 'utf8'
var loweredCase = false
for ( ; ; ) {
switch ( encoding ) {
case 'hex' :
return hexWrite ( this , string , offset , length )
case 'utf8' :
case 'utf-8' :
return utf8Write ( this , string , offset , length )
case 'ascii' :
return asciiWrite ( this , string , offset , length )
2017-02-20 22:19:56 +00:00
case 'latin1' :
2016-04-06 16:22:30 +00:00
case 'binary' :
2017-02-20 22:19:56 +00:00
return latin1Write ( this , string , offset , length )
2016-04-06 16:22:30 +00:00
case 'base64' :
// Warning: maxLength not taken into account in base64Write
return base64Write ( this , string , offset , length )
case 'ucs2' :
case 'ucs-2' :
case 'utf16le' :
case 'utf-16le' :
return ucs2Write ( this , string , offset , length )
default :
if ( loweredCase ) throw new TypeError ( 'Unknown encoding: ' + encoding )
encoding = ( '' + encoding ) . toLowerCase ( )
loweredCase = true
}
}
}
Buffer . prototype . toJSON = function toJSON ( ) {
return {
type : 'Buffer' ,
data : Array . prototype . slice . call ( this . _arr || this , 0 )
}
}
function base64Slice ( buf , start , end ) {
if ( start === 0 && end === buf . length ) {
return base64 . fromByteArray ( buf )
} else {
return base64 . fromByteArray ( buf . slice ( start , end ) )
}
}
function utf8Slice ( buf , start , end ) {
end = Math . min ( buf . length , end )
var res = [ ]
var i = start
while ( i < end ) {
var firstByte = buf [ i ]
var codePoint = null
var bytesPerSequence = ( firstByte > 0xEF ) ? 4
: ( firstByte > 0xDF ) ? 3
: ( firstByte > 0xBF ) ? 2
: 1
if ( i + bytesPerSequence <= end ) {
var secondByte , thirdByte , fourthByte , tempCodePoint
switch ( bytesPerSequence ) {
case 1 :
if ( firstByte < 0x80 ) {
codePoint = firstByte
}
break
case 2 :
secondByte = buf [ i + 1 ]
if ( ( secondByte & 0xC0 ) === 0x80 ) {
tempCodePoint = ( firstByte & 0x1F ) << 0x6 | ( secondByte & 0x3F )
if ( tempCodePoint > 0x7F ) {
codePoint = tempCodePoint
}
}
break
case 3 :
secondByte = buf [ i + 1 ]
thirdByte = buf [ i + 2 ]
if ( ( secondByte & 0xC0 ) === 0x80 && ( thirdByte & 0xC0 ) === 0x80 ) {
tempCodePoint = ( firstByte & 0xF ) << 0xC | ( secondByte & 0x3F ) << 0x6 | ( thirdByte & 0x3F )
if ( tempCodePoint > 0x7FF && ( tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF ) ) {
codePoint = tempCodePoint
}
}
break
case 4 :
secondByte = buf [ i + 1 ]
thirdByte = buf [ i + 2 ]
fourthByte = buf [ i + 3 ]
if ( ( secondByte & 0xC0 ) === 0x80 && ( thirdByte & 0xC0 ) === 0x80 && ( fourthByte & 0xC0 ) === 0x80 ) {
tempCodePoint = ( firstByte & 0xF ) << 0x12 | ( secondByte & 0x3F ) << 0xC | ( thirdByte & 0x3F ) << 0x6 | ( fourthByte & 0x3F )
if ( tempCodePoint > 0xFFFF && tempCodePoint < 0x110000 ) {
codePoint = tempCodePoint
}
}
}
}
if ( codePoint === null ) {
// we did not generate a valid codePoint so insert a
// replacement char (U+FFFD) and advance only 1 byte
codePoint = 0xFFFD
bytesPerSequence = 1
} else if ( codePoint > 0xFFFF ) {
// encode to utf16 (surrogate pair dance)
codePoint -= 0x10000
res . push ( codePoint >>> 10 & 0x3FF | 0xD800 )
codePoint = 0xDC00 | codePoint & 0x3FF
}
res . push ( codePoint )
i += bytesPerSequence
}
return decodeCodePointsArray ( res )
}
// Based on http://stackoverflow.com/a/22747272/680742, the browser with
// the lowest limit is Chrome, with 0x10000 args.
// We go 1 magnitude less, for safety
var MAX _ARGUMENTS _LENGTH = 0x1000
function decodeCodePointsArray ( codePoints ) {
var len = codePoints . length
if ( len <= MAX _ARGUMENTS _LENGTH ) {
return String . fromCharCode . apply ( String , codePoints ) // avoid extra slice()
}
// Decode in chunks to avoid "call stack size exceeded".
var res = ''
var i = 0
while ( i < len ) {
res += String . fromCharCode . apply (
String ,
codePoints . slice ( i , i += MAX _ARGUMENTS _LENGTH )
)
}
return res
}
function asciiSlice ( buf , start , end ) {
var ret = ''
end = Math . min ( buf . length , end )
2017-02-20 22:19:56 +00:00
for ( var i = start ; i < end ; ++ i ) {
2016-04-06 16:22:30 +00:00
ret += String . fromCharCode ( buf [ i ] & 0x7F )
}
return ret
}
2017-02-20 22:19:56 +00:00
function latin1Slice ( buf , start , end ) {
2016-04-06 16:22:30 +00:00
var ret = ''
end = Math . min ( buf . length , end )
2017-02-20 22:19:56 +00:00
for ( var i = start ; i < end ; ++ i ) {
2016-04-06 16:22:30 +00:00
ret += String . fromCharCode ( buf [ i ] )
}
return ret
}
function hexSlice ( buf , start , end ) {
var len = buf . length
if ( ! start || start < 0 ) start = 0
if ( ! end || end < 0 || end > len ) end = len
var out = ''
2017-02-20 22:19:56 +00:00
for ( var i = start ; i < end ; ++ i ) {
2016-04-06 16:22:30 +00:00
out += toHex ( buf [ i ] )
}
return out
}
function utf16leSlice ( buf , start , end ) {
var bytes = buf . slice ( start , end )
var res = ''
for ( var i = 0 ; i < bytes . length ; i += 2 ) {
res += String . fromCharCode ( bytes [ i ] + bytes [ i + 1 ] * 256 )
}
return res
}
Buffer . prototype . slice = function slice ( start , end ) {
var len = this . length
start = ~ ~ start
end = end === undefined ? len : ~ ~ end
if ( start < 0 ) {
start += len
if ( start < 0 ) start = 0
} else if ( start > len ) {
start = len
}
if ( end < 0 ) {
end += len
if ( end < 0 ) end = 0
} else if ( end > len ) {
end = len
}
if ( end < start ) end = start
var newBuf
if ( Buffer . TYPED _ARRAY _SUPPORT ) {
newBuf = this . subarray ( start , end )
newBuf . _ _proto _ _ = Buffer . prototype
} else {
var sliceLen = end - start
newBuf = new Buffer ( sliceLen , undefined )
2017-02-20 22:19:56 +00:00
for ( var i = 0 ; i < sliceLen ; ++ i ) {
2016-04-06 16:22:30 +00:00
newBuf [ i ] = this [ i + start ]
}
}
return newBuf
}
/ *
* Need to make sure that buffer isn ' t trying to write out of bounds .
* /
function checkOffset ( offset , ext , length ) {
if ( ( offset % 1 ) !== 0 || offset < 0 ) throw new RangeError ( 'offset is not uint' )
if ( offset + ext > length ) throw new RangeError ( 'Trying to access beyond buffer length' )
}
Buffer . prototype . readUIntLE = function readUIntLE ( offset , byteLength , noAssert ) {
offset = offset | 0
byteLength = byteLength | 0
if ( ! noAssert ) checkOffset ( offset , byteLength , this . length )
var val = this [ offset ]
var mul = 1
var i = 0
while ( ++ i < byteLength && ( mul *= 0x100 ) ) {
val += this [ offset + i ] * mul
}
return val
}
Buffer . prototype . readUIntBE = function readUIntBE ( offset , byteLength , noAssert ) {
offset = offset | 0
byteLength = byteLength | 0
if ( ! noAssert ) {
checkOffset ( offset , byteLength , this . length )
}
var val = this [ offset + -- byteLength ]
var mul = 1
while ( byteLength > 0 && ( mul *= 0x100 ) ) {
val += this [ offset + -- byteLength ] * mul
}
return val
}
Buffer . prototype . readUInt8 = function readUInt8 ( offset , noAssert ) {
if ( ! noAssert ) checkOffset ( offset , 1 , this . length )
return this [ offset ]
}
Buffer . prototype . readUInt16LE = function readUInt16LE ( offset , noAssert ) {
if ( ! noAssert ) checkOffset ( offset , 2 , this . length )
return this [ offset ] | ( this [ offset + 1 ] << 8 )
}
Buffer . prototype . readUInt16BE = function readUInt16BE ( offset , noAssert ) {
if ( ! noAssert ) checkOffset ( offset , 2 , this . length )
return ( this [ offset ] << 8 ) | this [ offset + 1 ]
}
Buffer . prototype . readUInt32LE = function readUInt32LE ( offset , noAssert ) {
if ( ! noAssert ) checkOffset ( offset , 4 , this . length )
return ( ( this [ offset ] ) |
( this [ offset + 1 ] << 8 ) |
( this [ offset + 2 ] << 16 ) ) +
( this [ offset + 3 ] * 0x1000000 )
}
Buffer . prototype . readUInt32BE = function readUInt32BE ( offset , noAssert ) {
if ( ! noAssert ) checkOffset ( offset , 4 , this . length )
return ( this [ offset ] * 0x1000000 ) +
( ( this [ offset + 1 ] << 16 ) |
( this [ offset + 2 ] << 8 ) |
this [ offset + 3 ] )
}
Buffer . prototype . readIntLE = function readIntLE ( offset , byteLength , noAssert ) {
offset = offset | 0
byteLength = byteLength | 0
if ( ! noAssert ) checkOffset ( offset , byteLength , this . length )
var val = this [ offset ]
var mul = 1
var i = 0
while ( ++ i < byteLength && ( mul *= 0x100 ) ) {
val += this [ offset + i ] * mul
}
mul *= 0x80
if ( val >= mul ) val -= Math . pow ( 2 , 8 * byteLength )
return val
}
Buffer . prototype . readIntBE = function readIntBE ( offset , byteLength , noAssert ) {
offset = offset | 0
byteLength = byteLength | 0
if ( ! noAssert ) checkOffset ( offset , byteLength , this . length )
var i = byteLength
var mul = 1
var val = this [ offset + -- i ]
while ( i > 0 && ( mul *= 0x100 ) ) {
val += this [ offset + -- i ] * mul
}
mul *= 0x80
if ( val >= mul ) val -= Math . pow ( 2 , 8 * byteLength )
return val
}
Buffer . prototype . readInt8 = function readInt8 ( offset , noAssert ) {
if ( ! noAssert ) checkOffset ( offset , 1 , this . length )
if ( ! ( this [ offset ] & 0x80 ) ) return ( this [ offset ] )
return ( ( 0xff - this [ offset ] + 1 ) * - 1 )
}
Buffer . prototype . readInt16LE = function readInt16LE ( offset , noAssert ) {
if ( ! noAssert ) checkOffset ( offset , 2 , this . length )
var val = this [ offset ] | ( this [ offset + 1 ] << 8 )
return ( val & 0x8000 ) ? val | 0xFFFF0000 : val
}
Buffer . prototype . readInt16BE = function readInt16BE ( offset , noAssert ) {
if ( ! noAssert ) checkOffset ( offset , 2 , this . length )
var val = this [ offset + 1 ] | ( this [ offset ] << 8 )
return ( val & 0x8000 ) ? val | 0xFFFF0000 : val
}
Buffer . prototype . readInt32LE = function readInt32LE ( offset , noAssert ) {
if ( ! noAssert ) checkOffset ( offset , 4 , this . length )
return ( this [ offset ] ) |
( this [ offset + 1 ] << 8 ) |
( this [ offset + 2 ] << 16 ) |
( this [ offset + 3 ] << 24 )
}
Buffer . prototype . readInt32BE = function readInt32BE ( offset , noAssert ) {
if ( ! noAssert ) checkOffset ( offset , 4 , this . length )
return ( this [ offset ] << 24 ) |
( this [ offset + 1 ] << 16 ) |
( this [ offset + 2 ] << 8 ) |
( this [ offset + 3 ] )
}
Buffer . prototype . readFloatLE = function readFloatLE ( offset , noAssert ) {
if ( ! noAssert ) checkOffset ( offset , 4 , this . length )
return ieee754 . read ( this , offset , true , 23 , 4 )
}
Buffer . prototype . readFloatBE = function readFloatBE ( offset , noAssert ) {
if ( ! noAssert ) checkOffset ( offset , 4 , this . length )
return ieee754 . read ( this , offset , false , 23 , 4 )
}
Buffer . prototype . readDoubleLE = function readDoubleLE ( offset , noAssert ) {
if ( ! noAssert ) checkOffset ( offset , 8 , this . length )
return ieee754 . read ( this , offset , true , 52 , 8 )
}
Buffer . prototype . readDoubleBE = function readDoubleBE ( offset , noAssert ) {
if ( ! noAssert ) checkOffset ( offset , 8 , this . length )
return ieee754 . read ( this , offset , false , 52 , 8 )
}
function checkInt ( buf , value , offset , ext , max , min ) {
2016-05-02 21:15:05 +00:00
if ( ! Buffer . isBuffer ( buf ) ) throw new TypeError ( '"buffer" argument must be a Buffer instance' )
if ( value > max || value < min ) throw new RangeError ( '"value" argument is out of bounds' )
if ( offset + ext > buf . length ) throw new RangeError ( 'Index out of range' )
2016-04-06 16:22:30 +00:00
}
Buffer . prototype . writeUIntLE = function writeUIntLE ( value , offset , byteLength , noAssert ) {
value = + value
offset = offset | 0
byteLength = byteLength | 0
2016-05-02 21:15:05 +00:00
if ( ! noAssert ) {
var maxBytes = Math . pow ( 2 , 8 * byteLength ) - 1
checkInt ( this , value , offset , byteLength , maxBytes , 0 )
}
2016-04-06 16:22:30 +00:00
var mul = 1
var i = 0
this [ offset ] = value & 0xFF
while ( ++ i < byteLength && ( mul *= 0x100 ) ) {
this [ offset + i ] = ( value / mul ) & 0xFF
}
return offset + byteLength
}
Buffer . prototype . writeUIntBE = function writeUIntBE ( value , offset , byteLength , noAssert ) {
value = + value
offset = offset | 0
byteLength = byteLength | 0
2016-05-02 21:15:05 +00:00
if ( ! noAssert ) {
var maxBytes = Math . pow ( 2 , 8 * byteLength ) - 1
checkInt ( this , value , offset , byteLength , maxBytes , 0 )
}
2016-04-06 16:22:30 +00:00
var i = byteLength - 1
var mul = 1
this [ offset + i ] = value & 0xFF
while ( -- i >= 0 && ( mul *= 0x100 ) ) {
this [ offset + i ] = ( value / mul ) & 0xFF
}
return offset + byteLength
}
Buffer . prototype . writeUInt8 = function writeUInt8 ( value , offset , noAssert ) {
value = + value
offset = offset | 0
if ( ! noAssert ) checkInt ( this , value , offset , 1 , 0xff , 0 )
if ( ! Buffer . TYPED _ARRAY _SUPPORT ) value = Math . floor ( value )
this [ offset ] = ( value & 0xff )
return offset + 1
}
function objectWriteUInt16 ( buf , value , offset , littleEndian ) {
if ( value < 0 ) value = 0xffff + value + 1
2017-02-20 22:19:56 +00:00
for ( var i = 0 , j = Math . min ( buf . length - offset , 2 ) ; i < j ; ++ i ) {
2016-04-06 16:22:30 +00:00
buf [ offset + i ] = ( value & ( 0xff << ( 8 * ( littleEndian ? i : 1 - i ) ) ) ) >>>
( littleEndian ? i : 1 - i ) * 8
}
}
Buffer . prototype . writeUInt16LE = function writeUInt16LE ( value , offset , noAssert ) {
value = + value
offset = offset | 0
if ( ! noAssert ) checkInt ( this , value , offset , 2 , 0xffff , 0 )
if ( Buffer . TYPED _ARRAY _SUPPORT ) {
this [ offset ] = ( value & 0xff )
this [ offset + 1 ] = ( value >>> 8 )
} else {
objectWriteUInt16 ( this , value , offset , true )
}
return offset + 2
}
Buffer . prototype . writeUInt16BE = function writeUInt16BE ( value , offset , noAssert ) {
value = + value
offset = offset | 0
if ( ! noAssert ) checkInt ( this , value , offset , 2 , 0xffff , 0 )
if ( Buffer . TYPED _ARRAY _SUPPORT ) {
this [ offset ] = ( value >>> 8 )
this [ offset + 1 ] = ( value & 0xff )
} else {
objectWriteUInt16 ( this , value , offset , false )
}
return offset + 2
}
function objectWriteUInt32 ( buf , value , offset , littleEndian ) {
if ( value < 0 ) value = 0xffffffff + value + 1
2017-02-20 22:19:56 +00:00
for ( var i = 0 , j = Math . min ( buf . length - offset , 4 ) ; i < j ; ++ i ) {
2016-04-06 16:22:30 +00:00
buf [ offset + i ] = ( value >>> ( littleEndian ? i : 3 - i ) * 8 ) & 0xff
}
}
Buffer . prototype . writeUInt32LE = function writeUInt32LE ( value , offset , noAssert ) {
value = + value
offset = offset | 0
if ( ! noAssert ) checkInt ( this , value , offset , 4 , 0xffffffff , 0 )
if ( Buffer . TYPED _ARRAY _SUPPORT ) {
this [ offset + 3 ] = ( value >>> 24 )
this [ offset + 2 ] = ( value >>> 16 )
this [ offset + 1 ] = ( value >>> 8 )
this [ offset ] = ( value & 0xff )
} else {
objectWriteUInt32 ( this , value , offset , true )
}
return offset + 4
}
Buffer . prototype . writeUInt32BE = function writeUInt32BE ( value , offset , noAssert ) {
value = + value
offset = offset | 0
if ( ! noAssert ) checkInt ( this , value , offset , 4 , 0xffffffff , 0 )
if ( Buffer . TYPED _ARRAY _SUPPORT ) {
this [ offset ] = ( value >>> 24 )
this [ offset + 1 ] = ( value >>> 16 )
this [ offset + 2 ] = ( value >>> 8 )
this [ offset + 3 ] = ( value & 0xff )
} else {
objectWriteUInt32 ( this , value , offset , false )
}
return offset + 4
}
Buffer . prototype . writeIntLE = function writeIntLE ( value , offset , byteLength , noAssert ) {
value = + value
offset = offset | 0
if ( ! noAssert ) {
var limit = Math . pow ( 2 , 8 * byteLength - 1 )
checkInt ( this , value , offset , byteLength , limit - 1 , - limit )
}
var i = 0
var mul = 1
2016-05-02 21:15:05 +00:00
var sub = 0
2016-04-06 16:22:30 +00:00
this [ offset ] = value & 0xFF
while ( ++ i < byteLength && ( mul *= 0x100 ) ) {
2016-05-02 21:15:05 +00:00
if ( value < 0 && sub === 0 && this [ offset + i - 1 ] !== 0 ) {
sub = 1
}
2016-04-06 16:22:30 +00:00
this [ offset + i ] = ( ( value / mul ) >> 0 ) - sub & 0xFF
}
return offset + byteLength
}
Buffer . prototype . writeIntBE = function writeIntBE ( value , offset , byteLength , noAssert ) {
value = + value
offset = offset | 0
if ( ! noAssert ) {
var limit = Math . pow ( 2 , 8 * byteLength - 1 )
checkInt ( this , value , offset , byteLength , limit - 1 , - limit )
}
var i = byteLength - 1
var mul = 1
2016-05-02 21:15:05 +00:00
var sub = 0
2016-04-06 16:22:30 +00:00
this [ offset + i ] = value & 0xFF
while ( -- i >= 0 && ( mul *= 0x100 ) ) {
2016-05-02 21:15:05 +00:00
if ( value < 0 && sub === 0 && this [ offset + i + 1 ] !== 0 ) {
sub = 1
}
2016-04-06 16:22:30 +00:00
this [ offset + i ] = ( ( value / mul ) >> 0 ) - sub & 0xFF
}
return offset + byteLength
}
Buffer . prototype . writeInt8 = function writeInt8 ( value , offset , noAssert ) {
value = + value
offset = offset | 0
if ( ! noAssert ) checkInt ( this , value , offset , 1 , 0x7f , - 0x80 )
if ( ! Buffer . TYPED _ARRAY _SUPPORT ) value = Math . floor ( value )
if ( value < 0 ) value = 0xff + value + 1
this [ offset ] = ( value & 0xff )
return offset + 1
}
Buffer . prototype . writeInt16LE = function writeInt16LE ( value , offset , noAssert ) {
value = + value
offset = offset | 0
if ( ! noAssert ) checkInt ( this , value , offset , 2 , 0x7fff , - 0x8000 )
if ( Buffer . TYPED _ARRAY _SUPPORT ) {
this [ offset ] = ( value & 0xff )
this [ offset + 1 ] = ( value >>> 8 )
} else {
objectWriteUInt16 ( this , value , offset , true )
}
return offset + 2
}
Buffer . prototype . writeInt16BE = function writeInt16BE ( value , offset , noAssert ) {
value = + value
offset = offset | 0
if ( ! noAssert ) checkInt ( this , value , offset , 2 , 0x7fff , - 0x8000 )
if ( Buffer . TYPED _ARRAY _SUPPORT ) {
this [ offset ] = ( value >>> 8 )
this [ offset + 1 ] = ( value & 0xff )
} else {
objectWriteUInt16 ( this , value , offset , false )
}
return offset + 2
}
Buffer . prototype . writeInt32LE = function writeInt32LE ( value , offset , noAssert ) {
value = + value
offset = offset | 0
if ( ! noAssert ) checkInt ( this , value , offset , 4 , 0x7fffffff , - 0x80000000 )
if ( Buffer . TYPED _ARRAY _SUPPORT ) {
this [ offset ] = ( value & 0xff )
this [ offset + 1 ] = ( value >>> 8 )
this [ offset + 2 ] = ( value >>> 16 )
this [ offset + 3 ] = ( value >>> 24 )
} else {
objectWriteUInt32 ( this , value , offset , true )
}
return offset + 4
}
Buffer . prototype . writeInt32BE = function writeInt32BE ( value , offset , noAssert ) {
value = + value
offset = offset | 0
if ( ! noAssert ) checkInt ( this , value , offset , 4 , 0x7fffffff , - 0x80000000 )
if ( value < 0 ) value = 0xffffffff + value + 1
if ( Buffer . TYPED _ARRAY _SUPPORT ) {
this [ offset ] = ( value >>> 24 )
this [ offset + 1 ] = ( value >>> 16 )
this [ offset + 2 ] = ( value >>> 8 )
this [ offset + 3 ] = ( value & 0xff )
} else {
objectWriteUInt32 ( this , value , offset , false )
}
return offset + 4
}
function checkIEEE754 ( buf , value , offset , ext , max , min ) {
2016-05-02 21:15:05 +00:00
if ( offset + ext > buf . length ) throw new RangeError ( 'Index out of range' )
if ( offset < 0 ) throw new RangeError ( 'Index out of range' )
2016-04-06 16:22:30 +00:00
}
function writeFloat ( buf , value , offset , littleEndian , noAssert ) {
if ( ! noAssert ) {
checkIEEE754 ( buf , value , offset , 4 , 3.4028234663852886 e + 38 , - 3.4028234663852886 e + 38 )
}
ieee754 . write ( buf , value , offset , littleEndian , 23 , 4 )
return offset + 4
}
Buffer . prototype . writeFloatLE = function writeFloatLE ( value , offset , noAssert ) {
return writeFloat ( this , value , offset , true , noAssert )
}
Buffer . prototype . writeFloatBE = function writeFloatBE ( value , offset , noAssert ) {
return writeFloat ( this , value , offset , false , noAssert )
}
function writeDouble ( buf , value , offset , littleEndian , noAssert ) {
if ( ! noAssert ) {
checkIEEE754 ( buf , value , offset , 8 , 1.7976931348623157 E + 308 , - 1.7976931348623157 E + 308 )
}
ieee754 . write ( buf , value , offset , littleEndian , 52 , 8 )
return offset + 8
}
Buffer . prototype . writeDoubleLE = function writeDoubleLE ( value , offset , noAssert ) {
return writeDouble ( this , value , offset , true , noAssert )
}
Buffer . prototype . writeDoubleBE = function writeDoubleBE ( value , offset , noAssert ) {
return writeDouble ( this , value , offset , false , noAssert )
}
// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
Buffer . prototype . copy = function copy ( target , targetStart , start , end ) {
if ( ! start ) start = 0
if ( ! end && end !== 0 ) end = this . length
if ( targetStart >= target . length ) targetStart = target . length
if ( ! targetStart ) targetStart = 0
if ( end > 0 && end < start ) end = start
// Copy 0 bytes; we're done
if ( end === start ) return 0
if ( target . length === 0 || this . length === 0 ) return 0
// Fatal error conditions
if ( targetStart < 0 ) {
throw new RangeError ( 'targetStart out of bounds' )
}
if ( start < 0 || start >= this . length ) throw new RangeError ( 'sourceStart out of bounds' )
if ( end < 0 ) throw new RangeError ( 'sourceEnd out of bounds' )
// Are we oob?
if ( end > this . length ) end = this . length
if ( target . length - targetStart < end - start ) {
end = target . length - targetStart + start
}
var len = end - start
var i
if ( this === target && start < targetStart && targetStart < end ) {
// descending copy from end
2017-02-20 22:19:56 +00:00
for ( i = len - 1 ; i >= 0 ; -- i ) {
2016-04-06 16:22:30 +00:00
target [ i + targetStart ] = this [ i + start ]
}
} else if ( len < 1000 || ! Buffer . TYPED _ARRAY _SUPPORT ) {
// ascending copy from start
2017-02-20 22:19:56 +00:00
for ( i = 0 ; i < len ; ++ i ) {
2016-04-06 16:22:30 +00:00
target [ i + targetStart ] = this [ i + start ]
}
} else {
Uint8Array . prototype . set . call (
target ,
this . subarray ( start , start + len ) ,
targetStart
)
}
return len
}
2016-05-02 21:15:05 +00:00
// Usage:
// buffer.fill(number[, offset[, end]])
// buffer.fill(buffer[, offset[, end]])
// buffer.fill(string[, offset[, end]][, encoding])
Buffer . prototype . fill = function fill ( val , start , end , encoding ) {
// Handle string cases:
if ( typeof val === 'string' ) {
if ( typeof start === 'string' ) {
encoding = start
start = 0
end = this . length
} else if ( typeof end === 'string' ) {
encoding = end
end = this . length
}
if ( val . length === 1 ) {
var code = val . charCodeAt ( 0 )
if ( code < 256 ) {
val = code
}
}
if ( encoding !== undefined && typeof encoding !== 'string' ) {
throw new TypeError ( 'encoding must be a string' )
}
if ( typeof encoding === 'string' && ! Buffer . isEncoding ( encoding ) ) {
throw new TypeError ( 'Unknown encoding: ' + encoding )
}
} else if ( typeof val === 'number' ) {
val = val & 255
}
2016-04-06 16:22:30 +00:00
2016-05-02 21:15:05 +00:00
// Invalid ranges are not set to a default, so can range check early.
if ( start < 0 || this . length < start || this . length < end ) {
throw new RangeError ( 'Out of range index' )
}
if ( end <= start ) {
return this
}
2016-04-06 16:22:30 +00:00
2016-05-02 21:15:05 +00:00
start = start >>> 0
end = end === undefined ? this . length : end >>> 0
2016-04-06 16:22:30 +00:00
2016-05-02 21:15:05 +00:00
if ( ! val ) val = 0
2016-04-06 16:22:30 +00:00
var i
2016-05-02 21:15:05 +00:00
if ( typeof val === 'number' ) {
2017-02-20 22:19:56 +00:00
for ( i = start ; i < end ; ++ i ) {
2016-05-02 21:15:05 +00:00
this [ i ] = val
2016-04-06 16:22:30 +00:00
}
} else {
2016-05-02 21:15:05 +00:00
var bytes = Buffer . isBuffer ( val )
? val
: utf8ToBytes ( new Buffer ( val , encoding ) . toString ( ) )
2016-04-06 16:22:30 +00:00
var len = bytes . length
2017-02-20 22:19:56 +00:00
for ( i = 0 ; i < end - start ; ++ i ) {
2016-05-02 21:15:05 +00:00
this [ i + start ] = bytes [ i % len ]
2016-04-06 16:22:30 +00:00
}
}
return this
}
// HELPER FUNCTIONS
// ================
var INVALID _BASE64 _RE = /[^+\/0-9A-Za-z-_]/g
function base64clean ( str ) {
// Node strips out invalid characters like \n and \t from the string, base64-js does not
str = stringtrim ( str ) . replace ( INVALID _BASE64 _RE , '' )
// Node converts strings with length < 2 to ''
if ( str . length < 2 ) return ''
// Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
while ( str . length % 4 !== 0 ) {
str = str + '='
}
return str
}
function stringtrim ( str ) {
if ( str . trim ) return str . trim ( )
return str . replace ( /^\s+|\s+$/g , '' )
}
function toHex ( n ) {
if ( n < 16 ) return '0' + n . toString ( 16 )
return n . toString ( 16 )
}
function utf8ToBytes ( string , units ) {
units = units || Infinity
var codePoint
var length = string . length
var leadSurrogate = null
var bytes = [ ]
2017-02-20 22:19:56 +00:00
for ( var i = 0 ; i < length ; ++ i ) {
2016-04-06 16:22:30 +00:00
codePoint = string . charCodeAt ( i )
// is surrogate component
if ( codePoint > 0xD7FF && codePoint < 0xE000 ) {
// last char was a lead
if ( ! leadSurrogate ) {
// no lead yet
if ( codePoint > 0xDBFF ) {
// unexpected trail
if ( ( units -= 3 ) > - 1 ) bytes . push ( 0xEF , 0xBF , 0xBD )
continue
} else if ( i + 1 === length ) {
// unpaired lead
if ( ( units -= 3 ) > - 1 ) bytes . push ( 0xEF , 0xBF , 0xBD )
continue
}
// valid lead
leadSurrogate = codePoint
continue
}
// 2 leads in a row
if ( codePoint < 0xDC00 ) {
if ( ( units -= 3 ) > - 1 ) bytes . push ( 0xEF , 0xBF , 0xBD )
leadSurrogate = codePoint
continue
}
// valid surrogate pair
codePoint = ( leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00 ) + 0x10000
} else if ( leadSurrogate ) {
// valid bmp char, but last char was a lead
if ( ( units -= 3 ) > - 1 ) bytes . push ( 0xEF , 0xBF , 0xBD )
}
leadSurrogate = null
// encode utf8
if ( codePoint < 0x80 ) {
if ( ( units -= 1 ) < 0 ) break
bytes . push ( codePoint )
} else if ( codePoint < 0x800 ) {
if ( ( units -= 2 ) < 0 ) break
bytes . push (
codePoint >> 0x6 | 0xC0 ,
codePoint & 0x3F | 0x80
)
} else if ( codePoint < 0x10000 ) {
if ( ( units -= 3 ) < 0 ) break
bytes . push (
codePoint >> 0xC | 0xE0 ,
codePoint >> 0x6 & 0x3F | 0x80 ,
codePoint & 0x3F | 0x80
)
} else if ( codePoint < 0x110000 ) {
if ( ( units -= 4 ) < 0 ) break
bytes . push (
codePoint >> 0x12 | 0xF0 ,
codePoint >> 0xC & 0x3F | 0x80 ,
codePoint >> 0x6 & 0x3F | 0x80 ,
codePoint & 0x3F | 0x80
)
} else {
throw new Error ( 'Invalid code point' )
}
}
return bytes
}
function asciiToBytes ( str ) {
var byteArray = [ ]
2017-02-20 22:19:56 +00:00
for ( var i = 0 ; i < str . length ; ++ i ) {
2016-04-06 16:22:30 +00:00
// Node's code seems to be doing this and not & 0x7F..
byteArray . push ( str . charCodeAt ( i ) & 0xFF )
}
return byteArray
}
function utf16leToBytes ( str , units ) {
var c , hi , lo
var byteArray = [ ]
2017-02-20 22:19:56 +00:00
for ( var i = 0 ; i < str . length ; ++ i ) {
2016-04-06 16:22:30 +00:00
if ( ( units -= 2 ) < 0 ) break
c = str . charCodeAt ( i )
hi = c >> 8
lo = c % 256
byteArray . push ( lo )
byteArray . push ( hi )
}
return byteArray
}
function base64ToBytes ( str ) {
return base64 . toByteArray ( base64clean ( str ) )
}
function blitBuffer ( src , dst , offset , length ) {
2017-02-20 22:19:56 +00:00
for ( var i = 0 ; i < length ; ++ i ) {
2016-04-06 16:22:30 +00:00
if ( ( i + offset >= dst . length ) || ( i >= src . length ) ) break
dst [ i + offset ] = src [ i ]
}
return i
}
2016-05-02 21:15:05 +00:00
function isnan ( val ) {
return val !== val // eslint-disable-line no-self-compare
}
2016-04-06 16:22:30 +00:00
} ) . call ( this , typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : { } )
} , { "base64-js" : 5 , "ieee754" : 6 , "isarray" : 7 } ] , 5 : [ function ( require , module , exports ) {
2016-05-02 21:15:05 +00:00
'use strict'
2016-04-06 16:22:30 +00:00
2017-02-20 22:19:56 +00:00
exports . byteLength = byteLength
2016-05-02 21:15:05 +00:00
exports . toByteArray = toByteArray
exports . fromByteArray = fromByteArray
2016-04-06 16:22:30 +00:00
2016-05-02 21:15:05 +00:00
var lookup = [ ]
var revLookup = [ ]
var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array
2016-04-06 16:22:30 +00:00
2017-02-20 22:19:56 +00:00
var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
for ( var i = 0 , len = code . length ; i < len ; ++ i ) {
lookup [ i ] = code [ i ]
revLookup [ code . charCodeAt ( i ) ] = i
2016-05-02 21:15:05 +00:00
}
2016-04-06 16:22:30 +00:00
2017-02-20 22:19:56 +00:00
revLookup [ '-' . charCodeAt ( 0 ) ] = 62
revLookup [ '_' . charCodeAt ( 0 ) ] = 63
2016-04-06 16:22:30 +00:00
2017-02-20 22:19:56 +00:00
function placeHoldersCount ( b64 ) {
2016-05-02 21:15:05 +00:00
var len = b64 . length
if ( len % 4 > 0 ) {
throw new Error ( 'Invalid string. Length must be a multiple of 4' )
}
2016-04-06 16:22:30 +00:00
2016-05-02 21:15:05 +00:00
// the number of equal signs (place holders)
// if there are two placeholders, than the two characters before it
// represent one byte
// if there is only one, then the three characters before it represent 2 bytes
// this is just a cheap hack to not do indexOf twice
2017-02-20 22:19:56 +00:00
return b64 [ len - 2 ] === '=' ? 2 : b64 [ len - 1 ] === '=' ? 1 : 0
}
2016-04-06 16:22:30 +00:00
2017-02-20 22:19:56 +00:00
function byteLength ( b64 ) {
2016-05-02 21:15:05 +00:00
// base64 is 4/3 + up to two characters of the original data
2017-02-20 22:19:56 +00:00
return b64 . length * 3 / 4 - placeHoldersCount ( b64 )
}
function toByteArray ( b64 ) {
var i , j , l , tmp , placeHolders , arr
var len = b64 . length
placeHolders = placeHoldersCount ( b64 )
2016-05-02 21:15:05 +00:00
arr = new Arr ( len * 3 / 4 - placeHolders )
2016-04-06 16:22:30 +00:00
2016-05-02 21:15:05 +00:00
// if there are placeholders, only get up to the last complete 4 chars
l = placeHolders > 0 ? len - 4 : len
2016-04-06 16:22:30 +00:00
2016-05-02 21:15:05 +00:00
var L = 0
2016-04-06 16:22:30 +00:00
2016-05-02 21:15:05 +00:00
for ( i = 0 , j = 0 ; i < l ; i += 4 , j += 3 ) {
tmp = ( revLookup [ b64 . charCodeAt ( i ) ] << 18 ) | ( revLookup [ b64 . charCodeAt ( i + 1 ) ] << 12 ) | ( revLookup [ b64 . charCodeAt ( i + 2 ) ] << 6 ) | revLookup [ b64 . charCodeAt ( i + 3 ) ]
arr [ L ++ ] = ( tmp >> 16 ) & 0xFF
arr [ L ++ ] = ( tmp >> 8 ) & 0xFF
arr [ L ++ ] = tmp & 0xFF
}
2016-04-06 16:22:30 +00:00
2016-05-02 21:15:05 +00:00
if ( placeHolders === 2 ) {
tmp = ( revLookup [ b64 . charCodeAt ( i ) ] << 2 ) | ( revLookup [ b64 . charCodeAt ( i + 1 ) ] >> 4 )
arr [ L ++ ] = tmp & 0xFF
} else if ( placeHolders === 1 ) {
tmp = ( revLookup [ b64 . charCodeAt ( i ) ] << 10 ) | ( revLookup [ b64 . charCodeAt ( i + 1 ) ] << 4 ) | ( revLookup [ b64 . charCodeAt ( i + 2 ) ] >> 2 )
arr [ L ++ ] = ( tmp >> 8 ) & 0xFF
arr [ L ++ ] = tmp & 0xFF
2016-04-06 16:22:30 +00:00
}
2016-05-02 21:15:05 +00:00
return arr
}
2016-04-06 16:22:30 +00:00
2016-05-02 21:15:05 +00:00
function tripletToBase64 ( num ) {
return lookup [ num >> 18 & 0x3F ] + lookup [ num >> 12 & 0x3F ] + lookup [ num >> 6 & 0x3F ] + lookup [ num & 0x3F ]
}
2016-04-06 16:22:30 +00:00
2016-05-02 21:15:05 +00:00
function encodeChunk ( uint8 , start , end ) {
var tmp
var output = [ ]
for ( var i = start ; i < end ; i += 3 ) {
tmp = ( uint8 [ i ] << 16 ) + ( uint8 [ i + 1 ] << 8 ) + ( uint8 [ i + 2 ] )
output . push ( tripletToBase64 ( tmp ) )
}
return output . join ( '' )
}
2016-04-06 16:22:30 +00:00
2016-05-02 21:15:05 +00:00
function fromByteArray ( uint8 ) {
var tmp
var len = uint8 . length
var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes
var output = ''
var parts = [ ]
var maxChunkLength = 16383 // must be multiple of 3
2016-04-06 16:22:30 +00:00
2016-05-02 21:15:05 +00:00
// go through the array every three bytes, we'll deal with trailing stuff later
for ( var i = 0 , len2 = len - extraBytes ; i < len2 ; i += maxChunkLength ) {
parts . push ( encodeChunk ( uint8 , i , ( i + maxChunkLength ) > len2 ? len2 : ( i + maxChunkLength ) ) )
}
2016-04-06 16:22:30 +00:00
2016-05-02 21:15:05 +00:00
// pad the end with zeros, but make sure to not forget the extra bytes
if ( extraBytes === 1 ) {
tmp = uint8 [ len - 1 ]
output += lookup [ tmp >> 2 ]
output += lookup [ ( tmp << 4 ) & 0x3F ]
output += '=='
} else if ( extraBytes === 2 ) {
tmp = ( uint8 [ len - 2 ] << 8 ) + ( uint8 [ len - 1 ] )
output += lookup [ tmp >> 10 ]
output += lookup [ ( tmp >> 4 ) & 0x3F ]
output += lookup [ ( tmp << 2 ) & 0x3F ]
output += '='
2016-04-06 16:22:30 +00:00
}
2016-05-02 21:15:05 +00:00
parts . push ( output )
return parts . join ( '' )
}
2016-04-06 16:22:30 +00:00
} , { } ] , 6 : [ function ( require , module , exports ) {
exports . read = function ( buffer , offset , isLE , mLen , nBytes ) {
var e , m
var eLen = nBytes * 8 - mLen - 1
var eMax = ( 1 << eLen ) - 1
var eBias = eMax >> 1
var nBits = - 7
var i = isLE ? ( nBytes - 1 ) : 0
var d = isLE ? - 1 : 1
var s = buffer [ offset + i ]
i += d
e = s & ( ( 1 << ( - nBits ) ) - 1 )
s >>= ( - nBits )
nBits += eLen
for ( ; nBits > 0 ; e = e * 256 + buffer [ offset + i ] , i += d , nBits -= 8 ) { }
m = e & ( ( 1 << ( - nBits ) ) - 1 )
e >>= ( - nBits )
nBits += mLen
for ( ; nBits > 0 ; m = m * 256 + buffer [ offset + i ] , i += d , nBits -= 8 ) { }
if ( e === 0 ) {
e = 1 - eBias
} else if ( e === eMax ) {
return m ? NaN : ( ( s ? - 1 : 1 ) * Infinity )
} else {
m = m + Math . pow ( 2 , mLen )
e = e - eBias
}
return ( s ? - 1 : 1 ) * m * Math . pow ( 2 , e - mLen )
}
exports . write = function ( buffer , value , offset , isLE , mLen , nBytes ) {
var e , m , c
var eLen = nBytes * 8 - mLen - 1
var eMax = ( 1 << eLen ) - 1
var eBias = eMax >> 1
var rt = ( mLen === 23 ? Math . pow ( 2 , - 24 ) - Math . pow ( 2 , - 77 ) : 0 )
var i = isLE ? 0 : ( nBytes - 1 )
var d = isLE ? 1 : - 1
var s = value < 0 || ( value === 0 && 1 / value < 0 ) ? 1 : 0
value = Math . abs ( value )
if ( isNaN ( value ) || value === Infinity ) {
m = isNaN ( value ) ? 1 : 0
e = eMax
} else {
e = Math . floor ( Math . log ( value ) / Math . LN2 )
if ( value * ( c = Math . pow ( 2 , - e ) ) < 1 ) {
e --
c *= 2
}
if ( e + eBias >= 1 ) {
value += rt / c
} else {
value += rt * Math . pow ( 2 , 1 - eBias )
}
if ( value * c >= 2 ) {
e ++
c /= 2
}
if ( e + eBias >= eMax ) {
m = 0
e = eMax
} else if ( e + eBias >= 1 ) {
m = ( value * c - 1 ) * Math . pow ( 2 , mLen )
e = e + eBias
} else {
m = value * Math . pow ( 2 , eBias - 1 ) * Math . pow ( 2 , mLen )
e = 0
}
}
for ( ; mLen >= 8 ; buffer [ offset + i ] = m & 0xff , i += d , m /= 256 , mLen -= 8 ) { }
e = ( e << mLen ) | m
eLen += mLen
for ( ; eLen > 0 ; buffer [ offset + i ] = e & 0xff , i += d , e /= 256 , eLen -= 8 ) { }
buffer [ offset + i - d ] |= s * 128
}
} , { } ] , 7 : [ function ( require , module , exports ) {
var toString = { } . toString ;
module . exports = Array . isArray || function ( arr ) {
return toString . call ( arr ) == '[object Array]' ;
} ;
} , { } ] , 8 : [ function ( require , module , exports ) {
( function ( process ) {
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
// resolves . and .. elements in a path array with directory names there
// must be no slashes, empty elements, or device names (c:\) in the array
// (so also no leading and trailing slashes - it does not distinguish
// relative and absolute paths)
function normalizeArray ( parts , allowAboveRoot ) {
// if the path tries to go above the root, `up` ends up > 0
var up = 0 ;
for ( var i = parts . length - 1 ; i >= 0 ; i -- ) {
var last = parts [ i ] ;
if ( last === '.' ) {
parts . splice ( i , 1 ) ;
} else if ( last === '..' ) {
parts . splice ( i , 1 ) ;
up ++ ;
} else if ( up ) {
parts . splice ( i , 1 ) ;
up -- ;
}
}
// if the path is allowed to go above the root, restore leading ..s
if ( allowAboveRoot ) {
for ( ; up -- ; up ) {
parts . unshift ( '..' ) ;
}
}
return parts ;
}
// Split a filename into [root, dir, basename, ext], unix version
// 'root' is just a slash, or nothing.
var splitPathRe =
/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/ ;
var splitPath = function ( filename ) {
return splitPathRe . exec ( filename ) . slice ( 1 ) ;
} ;
// path.resolve([from ...], to)
// posix version
exports . resolve = function ( ) {
var resolvedPath = '' ,
resolvedAbsolute = false ;
for ( var i = arguments . length - 1 ; i >= - 1 && ! resolvedAbsolute ; i -- ) {
var path = ( i >= 0 ) ? arguments [ i ] : process . cwd ( ) ;
// Skip empty and invalid entries
if ( typeof path !== 'string' ) {
throw new TypeError ( 'Arguments to path.resolve must be strings' ) ;
} else if ( ! path ) {
continue ;
}
resolvedPath = path + '/' + resolvedPath ;
resolvedAbsolute = path . charAt ( 0 ) === '/' ;
}
// At this point the path should be resolved to a full absolute path, but
// handle relative paths to be safe (might happen when process.cwd() fails)
// Normalize the path
resolvedPath = normalizeArray ( filter ( resolvedPath . split ( '/' ) , function ( p ) {
return ! ! p ;
} ) , ! resolvedAbsolute ) . join ( '/' ) ;
return ( ( resolvedAbsolute ? '/' : '' ) + resolvedPath ) || '.' ;
} ;
// path.normalize(path)
// posix version
exports . normalize = function ( path ) {
var isAbsolute = exports . isAbsolute ( path ) ,
trailingSlash = substr ( path , - 1 ) === '/' ;
// Normalize the path
path = normalizeArray ( filter ( path . split ( '/' ) , function ( p ) {
return ! ! p ;
} ) , ! isAbsolute ) . join ( '/' ) ;
if ( ! path && ! isAbsolute ) {
path = '.' ;
}
if ( path && trailingSlash ) {
path += '/' ;
}
return ( isAbsolute ? '/' : '' ) + path ;
} ;
// posix version
exports . isAbsolute = function ( path ) {
return path . charAt ( 0 ) === '/' ;
} ;
// posix version
exports . join = function ( ) {
var paths = Array . prototype . slice . call ( arguments , 0 ) ;
return exports . normalize ( filter ( paths , function ( p , index ) {
if ( typeof p !== 'string' ) {
throw new TypeError ( 'Arguments to path.join must be strings' ) ;
}
return p ;
} ) . join ( '/' ) ) ;
} ;
// path.relative(from, to)
// posix version
exports . relative = function ( from , to ) {
from = exports . resolve ( from ) . substr ( 1 ) ;
to = exports . resolve ( to ) . substr ( 1 ) ;
function trim ( arr ) {
var start = 0 ;
for ( ; start < arr . length ; start ++ ) {
if ( arr [ start ] !== '' ) break ;
}
var end = arr . length - 1 ;
for ( ; end >= 0 ; end -- ) {
if ( arr [ end ] !== '' ) break ;
}
if ( start > end ) return [ ] ;
return arr . slice ( start , end - start + 1 ) ;
}
var fromParts = trim ( from . split ( '/' ) ) ;
var toParts = trim ( to . split ( '/' ) ) ;
var length = Math . min ( fromParts . length , toParts . length ) ;
var samePartsLength = length ;
for ( var i = 0 ; i < length ; i ++ ) {
if ( fromParts [ i ] !== toParts [ i ] ) {
samePartsLength = i ;
break ;
}
}
var outputParts = [ ] ;
for ( var i = samePartsLength ; i < fromParts . length ; i ++ ) {
outputParts . push ( '..' ) ;
}
outputParts = outputParts . concat ( toParts . slice ( samePartsLength ) ) ;
return outputParts . join ( '/' ) ;
} ;
exports . sep = '/' ;
exports . delimiter = ':' ;
exports . dirname = function ( path ) {
var result = splitPath ( path ) ,
root = result [ 0 ] ,
dir = result [ 1 ] ;
if ( ! root && ! dir ) {
// No dirname whatsoever
return '.' ;
}
if ( dir ) {
// It has a dirname, strip trailing slash
dir = dir . substr ( 0 , dir . length - 1 ) ;
}
return root + dir ;
} ;
exports . basename = function ( path , ext ) {
var f = splitPath ( path ) [ 2 ] ;
// TODO: make this comparison case-insensitive on windows?
if ( ext && f . substr ( - 1 * ext . length ) === ext ) {
f = f . substr ( 0 , f . length - ext . length ) ;
}
return f ;
} ;
exports . extname = function ( path ) {
return splitPath ( path ) [ 3 ] ;
} ;
function filter ( xs , f ) {
if ( xs . filter ) return xs . filter ( f ) ;
var res = [ ] ;
for ( var i = 0 ; i < xs . length ; i ++ ) {
if ( f ( xs [ i ] , i , xs ) ) res . push ( xs [ i ] ) ;
}
return res ;
}
// String.prototype.substr - negative index don't work in IE8
var substr = 'ab' . substr ( - 1 ) === 'b'
? function ( str , start , len ) { return str . substr ( start , len ) }
: function ( str , start , len ) {
if ( start < 0 ) start = str . length + start ;
return str . substr ( start , len ) ;
}
;
} ) . call ( this , require ( '_process' ) )
} , { "_process" : 9 } ] , 9 : [ function ( require , module , exports ) {
// shim for using process in browser
var process = module . exports = { } ;
2017-02-20 22:19:56 +00:00
// cached from whatever global is present so that test runners that stub it
// don't break things. But we need to wrap it in a try catch in case it is
// wrapped in strict mode code which doesn't define any globals. It's inside a
// function because try/catches deoptimize in certain engines.
var cachedSetTimeout ;
var cachedClearTimeout ;
function defaultSetTimout ( ) {
throw new Error ( 'setTimeout has not been defined' ) ;
}
function defaultClearTimeout ( ) {
throw new Error ( 'clearTimeout has not been defined' ) ;
}
( function ( ) {
try {
if ( typeof setTimeout === 'function' ) {
cachedSetTimeout = setTimeout ;
} else {
cachedSetTimeout = defaultSetTimout ;
}
} catch ( e ) {
cachedSetTimeout = defaultSetTimout ;
}
try {
if ( typeof clearTimeout === 'function' ) {
cachedClearTimeout = clearTimeout ;
} else {
cachedClearTimeout = defaultClearTimeout ;
}
} catch ( e ) {
cachedClearTimeout = defaultClearTimeout ;
}
} ( ) )
function runTimeout ( fun ) {
if ( cachedSetTimeout === setTimeout ) {
//normal enviroments in sane situations
return setTimeout ( fun , 0 ) ;
}
// if setTimeout wasn't available but was latter defined
if ( ( cachedSetTimeout === defaultSetTimout || ! cachedSetTimeout ) && setTimeout ) {
cachedSetTimeout = setTimeout ;
return setTimeout ( fun , 0 ) ;
}
try {
// when when somebody has screwed with setTimeout but no I.E. maddness
return cachedSetTimeout ( fun , 0 ) ;
} catch ( e ) {
try {
// When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
return cachedSetTimeout . call ( null , fun , 0 ) ;
} catch ( e ) {
// same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
return cachedSetTimeout . call ( this , fun , 0 ) ;
}
}
}
function runClearTimeout ( marker ) {
if ( cachedClearTimeout === clearTimeout ) {
//normal enviroments in sane situations
return clearTimeout ( marker ) ;
}
// if clearTimeout wasn't available but was latter defined
if ( ( cachedClearTimeout === defaultClearTimeout || ! cachedClearTimeout ) && clearTimeout ) {
cachedClearTimeout = clearTimeout ;
return clearTimeout ( marker ) ;
}
try {
// when when somebody has screwed with setTimeout but no I.E. maddness
return cachedClearTimeout ( marker ) ;
} catch ( e ) {
try {
// When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
return cachedClearTimeout . call ( null , marker ) ;
} catch ( e ) {
// same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
// Some versions of I.E. have different rules for clearTimeout vs setTimeout
return cachedClearTimeout . call ( this , marker ) ;
}
}
}
2016-04-06 16:22:30 +00:00
var queue = [ ] ;
var draining = false ;
var currentQueue ;
var queueIndex = - 1 ;
function cleanUpNextTick ( ) {
2016-08-08 02:03:35 +00:00
if ( ! draining || ! currentQueue ) {
return ;
}
2016-04-06 16:22:30 +00:00
draining = false ;
if ( currentQueue . length ) {
queue = currentQueue . concat ( queue ) ;
} else {
queueIndex = - 1 ;
}
if ( queue . length ) {
drainQueue ( ) ;
}
}
function drainQueue ( ) {
if ( draining ) {
return ;
}
2017-02-20 22:19:56 +00:00
var timeout = runTimeout ( cleanUpNextTick ) ;
2016-04-06 16:22:30 +00:00
draining = true ;
var len = queue . length ;
while ( len ) {
currentQueue = queue ;
queue = [ ] ;
while ( ++ queueIndex < len ) {
if ( currentQueue ) {
currentQueue [ queueIndex ] . run ( ) ;
}
}
queueIndex = - 1 ;
len = queue . length ;
}
currentQueue = null ;
draining = false ;
2017-02-20 22:19:56 +00:00
runClearTimeout ( timeout ) ;
2016-04-06 16:22:30 +00:00
}
process . nextTick = function ( fun ) {
var args = new Array ( arguments . length - 1 ) ;
if ( arguments . length > 1 ) {
for ( var i = 1 ; i < arguments . length ; i ++ ) {
args [ i - 1 ] = arguments [ i ] ;
}
}
queue . push ( new Item ( fun , args ) ) ;
if ( queue . length === 1 && ! draining ) {
2017-02-20 22:19:56 +00:00
runTimeout ( drainQueue ) ;
2016-04-06 16:22:30 +00:00
}
} ;
// v8 likes predictible objects
function Item ( fun , array ) {
this . fun = fun ;
this . array = array ;
}
Item . prototype . run = function ( ) {
this . fun . apply ( null , this . array ) ;
} ;
process . title = 'browser' ;
process . browser = true ;
process . env = { } ;
process . argv = [ ] ;
process . version = '' ; // empty string to avoid regexp issues
process . versions = { } ;
function noop ( ) { }
process . on = noop ;
process . addListener = noop ;
process . once = noop ;
process . off = noop ;
process . removeListener = noop ;
process . removeAllListeners = noop ;
process . emit = noop ;
process . binding = function ( name ) {
throw new Error ( 'process.binding is not supported' ) ;
} ;
process . cwd = function ( ) { return '/' } ;
process . chdir = function ( dir ) {
throw new Error ( 'process.chdir is not supported' ) ;
} ;
process . umask = function ( ) { return 0 ; } ;
} , { } ] , 10 : [ function ( require , module , exports ) {
var ohm = require ( '..' ) ;
2016-08-07 19:41:10 +00:00
module . exports = ohm . makeRecipe ( function ( ) {
var decl = this . newGrammar ( "BuiltInRules" )
. withSource ( "BuiltInRules {\n\n alnum (an alpha-numeric character)\n = letter\n | digit\n\n letter (a letter)\n = lower\n | upper\n | unicodeLtmo\n\n digit (a digit)\n = \"0\"..\"9\"\n\n hexDigit (a hexadecimal digit)\n = digit\n | \"a\"..\"f\"\n | \"A\"..\"F\"\n\n ListOf<elem, sep>\n = NonemptyListOf<elem, sep>\n | EmptyListOf<elem, sep>\n\n NonemptyListOf<elem, sep>\n = elem (sep elem)*\n\n EmptyListOf<elem, sep>\n = /* nothing */\n\n listOf<elem, sep>\n = nonemptyListOf<elem, sep>\n | emptyListOf<elem, sep>\n\n nonemptyListOf<elem, sep>\n = elem (sep elem)*\n\n emptyListOf<elem, sep>\n = /* nothing */\n\n}" )
return decl
. define ( "alnum" , [ ] , this . alt ( this . app ( "letter" ) . withInterval ( decl . sourceInterval ( 60 , 66 ) ) , this . app ( "digit" ) . withInterval ( decl . sourceInterval ( 73 , 78 ) ) ) . withInterval ( decl . sourceInterval ( 60 , 78 ) ) , "an alpha-numeric character" )
. define ( "letter" , [ ] , this . alt ( this . app ( "lower" ) . withInterval ( decl . sourceInterval ( 107 , 112 ) ) , this . app ( "upper" ) . withInterval ( decl . sourceInterval ( 119 , 124 ) ) , this . app ( "unicodeLtmo" ) . withInterval ( decl . sourceInterval ( 131 , 142 ) ) ) . withInterval ( decl . sourceInterval ( 107 , 142 ) ) , "a letter" )
. define ( "digit" , [ ] , this . range ( "0" , "9" ) . withInterval ( decl . sourceInterval ( 169 , 177 ) ) , "a digit" )
. define ( "hexDigit" , [ ] , this . alt ( this . app ( "digit" ) . withInterval ( decl . sourceInterval ( 219 , 224 ) ) , this . range ( "a" , "f" ) . withInterval ( decl . sourceInterval ( 231 , 239 ) ) , this . range ( "A" , "F" ) . withInterval ( decl . sourceInterval ( 246 , 254 ) ) ) . withInterval ( decl . sourceInterval ( 219 , 254 ) ) , "a hexadecimal digit" )
. define ( "ListOf" , [ "elem" , "sep" ] , this . alt ( this . app ( "NonemptyListOf" , [ this . param ( 0 ) , this . param ( 1 ) ] ) . withInterval ( decl . sourceInterval ( 282 , 307 ) ) , this . app ( "EmptyListOf" , [ this . param ( 0 ) , this . param ( 1 ) ] ) . withInterval ( decl . sourceInterval ( 314 , 336 ) ) ) . withInterval ( decl . sourceInterval ( 282 , 336 ) ) )
. define ( "NonemptyListOf" , [ "elem" , "sep" ] , this . seq ( this . param ( 0 ) , this . star ( this . seq ( this . param ( 1 ) , this . param ( 0 ) ) . withInterval ( decl . sourceInterval ( 378 , 386 ) ) ) . withInterval ( decl . sourceInterval ( 377 , 388 ) ) ) . withInterval ( decl . sourceInterval ( 372 , 388 ) ) )
. define ( "EmptyListOf" , [ "elem" , "sep" ] , this . seq ( ) . withInterval ( decl . sourceInterval ( 438 , 438 ) ) )
. define ( "listOf" , [ "elem" , "sep" ] , this . alt ( this . app ( "nonemptyListOf" , [ this . param ( 0 ) , this . param ( 1 ) ] ) . withInterval ( decl . sourceInterval ( 462 , 487 ) ) , this . app ( "emptyListOf" , [ this . param ( 0 ) , this . param ( 1 ) ] ) . withInterval ( decl . sourceInterval ( 494 , 516 ) ) ) . withInterval ( decl . sourceInterval ( 462 , 516 ) ) )
. define ( "nonemptyListOf" , [ "elem" , "sep" ] , this . seq ( this . param ( 0 ) , this . star ( this . seq ( this . param ( 1 ) , this . param ( 0 ) ) . withInterval ( decl . sourceInterval ( 558 , 566 ) ) ) . withInterval ( decl . sourceInterval ( 557 , 568 ) ) ) . withInterval ( decl . sourceInterval ( 552 , 568 ) ) )
. define ( "emptyListOf" , [ "elem" , "sep" ] , this . seq ( ) . withInterval ( decl . sourceInterval ( 616 , 616 ) ) )
. build ( ) ;
} ) ;
2016-04-06 16:22:30 +00:00
} , { ".." : 50 } ] , 11 : [ function ( require , module , exports ) {
var ohm = require ( '..' ) ;
2016-08-07 19:41:10 +00:00
module . exports = ohm . makeRecipe ( function ( ) {
var decl = this . newGrammar ( "Ohm" )
. withSource ( "Ohm {\n\n Grammars\n = Grammar*\n\n Grammar\n = ident SuperGrammar? \"{\" Rule* \"}\"\n\n SuperGrammar\n = \"<:\" ident\n\n Rule\n = ident Formals? ruleDescr? \"=\" RuleBody -- define\n | ident Formals? \":=\" RuleBody -- override\n | ident Formals? \"+=\" RuleBody -- extend\n\n RuleBody\n = \"|\"? TopLevelTerm (\"|\" TopLevelTerm)*\n\n TopLevelTerm\n = Seq caseName -- inline\n | Seq\n\n Formals\n = \"<\" ListOf<ident, \",\"> \">\"\n\n Params\n = \"<\" ListOf<Seq, \",\"> \">\"\n\n Alt\n = Seq (\"|\" Seq)*\n\n Seq\n = Iter*\n\n Iter\n = Pred \"*\" -- star\n | Pred \"+\" -- plus\n | Pred \"?\" -- opt\n | Pred\n\n Pred\n = \"~\" Lex -- not\n | \"&\" Lex -- lookahead\n | Lex\n\n Lex\n = \"#\" Base -- lex\n | Base\n\n Base\n = ident Params? ~(ruleDescr? \"=\" | \":=\" | \"+=\") -- application\n | terminal \"..\" terminal -- range\n | terminal -- terminal\n | \"(\" Alt \")\" -- paren\n\n ruleDescr (a rule description)\n = \"(\" ruleDescrText \")\"\n\n ruleDescrText\n = (~\")\" any)*\n\n caseName\n = \"--\" (~\"\\n\" space)* name (~\"\\n\" space)* (\"\\n\" | &\"}\")\n\n name (a name)\n = nameFirst nameRest*\n\n nameFirst\n = \"_\"\n | letter\n\n nameRest\n = \"_\"\n | alnum\n\n ident (an identifier)\n = name\n\n terminal\n = \"\\\"\" terminalChar* \"\\\"\"\n\n terminalChar\n = escapeChar\n | ~\"\\\\\" ~\"\\\"\" ~\"\\n\" any\n\n escapeChar (an escape sequence)\n = \"\\\\\\\\\" -- backslash\n | \"\\\\\\\"\" -- doubleQuote\n | \"\\\\\\'\" -- singleQuote\n | \"\\\\b\" -- backspace\n | \"\\\\n\" -- lineFeed\n | \"\\\\r\" -- carriageReturn\n | \"\\\\t\" -- tab\n | \"\\\\u\" hexDigit hexDigit hexDigit hexDigit -- unicodeEscape\n | \"\\\\x\" hexDigit hexDigit -- hexEscape\n\n space\n += comment\n\n comment\n = \"//\" (~\"\\n\" any)* \"\\n\" -- singleLine\n | \"/*\" (~\"*/\" any)* \"*/\" -- multiLine\n\n tokens = token*\n\n token = caseName | comment | ident | operator | punctuation | terminal | any\n\n operator = \"<:\" | \"=\" | \":=\" | \"+=\" | \"*\" | \"+\" | \"?\" | \"~\" | \"&\"\n\n punctuation = \"<\" | \">\" | \",\" | \"--\"\n}" )
. withDefaultStartRule ( "Grammars" )
return decl
. define ( "Grammars" , [ ] , this . star ( this . app ( "Grammar" ) . withInterval ( decl . sourceInterval ( 24 , 31 ) ) ) . withInterval ( decl . sourceInterval ( 24 , 32 ) ) )
. define ( "Grammar" , [ ] , this . seq ( this . app ( "ident" ) . withInterval ( decl . sourceInterval ( 50 , 55 ) ) , this . opt ( this . app ( "SuperGrammar" ) . withInterval ( decl . sourceInterval ( 56 , 68 ) ) ) . withInterval ( decl . sourceInterval ( 56 , 69 ) ) , this . terminal ( "{" ) . withInterval ( decl . sourceInterval ( 70 , 73 ) ) , this . star ( this . app ( "Rule" ) . withInterval ( decl . sourceInterval ( 74 , 78 ) ) ) . withInterval ( decl . sourceInterval ( 74 , 79 ) ) , this . terminal ( "}" ) . withInterval ( decl . sourceInterval ( 80 , 83 ) ) ) . withInterval ( decl . sourceInterval ( 50 , 83 ) ) )
. define ( "SuperGrammar" , [ ] , this . seq ( this . terminal ( "<:" ) . withInterval ( decl . sourceInterval ( 106 , 110 ) ) , this . app ( "ident" ) . withInterval ( decl . sourceInterval ( 111 , 116 ) ) ) . withInterval ( decl . sourceInterval ( 106 , 116 ) ) )
. define ( "Rule_define" , [ ] , this . seq ( this . app ( "ident" ) . withInterval ( decl . sourceInterval ( 131 , 136 ) ) , this . opt ( this . app ( "Formals" ) . withInterval ( decl . sourceInterval ( 137 , 144 ) ) ) . withInterval ( decl . sourceInterval ( 137 , 145 ) ) , this . opt ( this . app ( "ruleDescr" ) . withInterval ( decl . sourceInterval ( 146 , 155 ) ) ) . withInterval ( decl . sourceInterval ( 146 , 156 ) ) , this . terminal ( "=" ) . withInterval ( decl . sourceInterval ( 157 , 160 ) ) , this . app ( "RuleBody" ) . withInterval ( decl . sourceInterval ( 162 , 170 ) ) ) . withInterval ( decl . sourceInterval ( 131 , 170 ) ) )
. define ( "Rule_override" , [ ] , this . seq ( this . app ( "ident" ) . withInterval ( decl . sourceInterval ( 188 , 193 ) ) , this . opt ( this . app ( "Formals" ) . withInterval ( decl . sourceInterval ( 194 , 201 ) ) ) . withInterval ( decl . sourceInterval ( 194 , 202 ) ) , this . terminal ( ":=" ) . withInterval ( decl . sourceInterval ( 214 , 218 ) ) , this . app ( "RuleBody" ) . withInterval ( decl . sourceInterval ( 219 , 227 ) ) ) . withInterval ( decl . sourceInterval ( 188 , 227 ) ) )
. define ( "Rule_extend" , [ ] , this . seq ( this . app ( "ident" ) . withInterval ( decl . sourceInterval ( 247 , 252 ) ) , this . opt ( this . app ( "Formals" ) . withInterval ( decl . sourceInterval ( 253 , 260 ) ) ) . withInterval ( decl . sourceInterval ( 253 , 261 ) ) , this . terminal ( "+=" ) . withInterval ( decl . sourceInterval ( 273 , 277 ) ) , this . app ( "RuleBody" ) . withInterval ( decl . sourceInterval ( 278 , 286 ) ) ) . withInterval ( decl . sourceInterval ( 247 , 286 ) ) )
. define ( "Rule" , [ ] , this . alt ( this . app ( "Rule_define" ) . withInterval ( decl . sourceInterval ( 131 , 170 ) ) , this . app ( "Rule_override" ) . withInterval ( decl . sourceInterval ( 188 , 227 ) ) , this . app ( "Rule_extend" ) . withInterval ( decl . sourceInterval ( 247 , 286 ) ) ) . withInterval ( decl . sourceInterval ( 131 , 297 ) ) )
. define ( "RuleBody" , [ ] , this . seq ( this . opt ( this . terminal ( "|" ) . withInterval ( decl . sourceInterval ( 316 , 319 ) ) ) . withInterval ( decl . sourceInterval ( 316 , 320 ) ) , this . app ( "TopLevelTerm" ) . withInterval ( decl . sourceInterval ( 321 , 333 ) ) , this . star ( this . seq ( this . terminal ( "|" ) . withInterval ( decl . sourceInterval ( 335 , 338 ) ) , this . app ( "TopLevelTerm" ) . withInterval ( decl . sourceInterval ( 339 , 351 ) ) ) . withInterval ( decl . sourceInterval ( 335 , 351 ) ) ) . withInterval ( decl . sourceInterval ( 334 , 353 ) ) ) . withInterval ( decl . sourceInterval ( 316 , 353 ) ) )
. define ( "TopLevelTerm_inline" , [ ] , this . seq ( this . app ( "Seq" ) . withInterval ( decl . sourceInterval ( 376 , 379 ) ) , this . app ( "caseName" ) . withInterval ( decl . sourceInterval ( 380 , 388 ) ) ) . withInterval ( decl . sourceInterval ( 376 , 388 ) ) )
. define ( "TopLevelTerm" , [ ] , this . alt ( this . app ( "TopLevelTerm_inline" ) . withInterval ( decl . sourceInterval ( 376 , 388 ) ) , this . app ( "Seq" ) . withInterval ( decl . sourceInterval ( 406 , 409 ) ) ) . withInterval ( decl . sourceInterval ( 376 , 409 ) ) )
. define ( "Formals" , [ ] , this . seq ( this . terminal ( "<" ) . withInterval ( decl . sourceInterval ( 427 , 430 ) ) , this . app ( "ListOf" , [ this . app ( "ident" ) . withInterval ( decl . sourceInterval ( 438 , 443 ) ) , this . terminal ( "," ) . withInterval ( decl . sourceInterval ( 445 , 448 ) ) ] ) . withInterval ( decl . sourceInterval ( 431 , 449 ) ) , this . terminal ( ">" ) . withInterval ( decl . sourceInterval ( 450 , 453 ) ) ) . withInterval ( decl . sourceInterval ( 427 , 453 ) ) )
. define ( "Params" , [ ] , this . seq ( this . terminal ( "<" ) . withInterval ( decl . sourceInterval ( 470 , 473 ) ) , this . app ( "ListOf" , [ this . app ( "Seq" ) . withInterval ( decl . sourceInterval ( 481 , 484 ) ) , this . terminal ( "," ) . withInterval ( decl . sourceInterval ( 486 , 489 ) ) ] ) . withInterval ( decl . sourceInterval ( 474 , 490 ) ) , this . terminal ( ">" ) . withInterval ( decl . sourceInterval ( 491 , 494 ) ) ) . withInterval ( decl . sourceInterval ( 470 , 494 ) ) )
. define ( "Alt" , [ ] , this . seq ( this . app ( "Seq" ) . withInterval ( decl . sourceInterval ( 508 , 511 ) ) , this . star ( this . seq ( this . terminal ( "|" ) . withInterval ( decl . sourceInterval ( 513 , 516 ) ) , this . app ( "Seq" ) . withInterval ( decl . sourceInterval ( 517 , 520 ) ) ) . withInterval ( decl . sourceInterval ( 513 , 520 ) ) ) . withInterval ( decl . sourceInterval ( 512 , 522 ) ) ) . withInterval ( decl . sourceInterval ( 508 , 522 ) ) )
. define ( "Seq" , [ ] , this . star ( this . app ( "Iter" ) . withInterval ( decl . sourceInterval ( 536 , 540 ) ) ) . withInterval ( decl . sourceInterval ( 536 , 541 ) ) )
. define ( "Iter_star" , [ ] , this . seq ( this . app ( "Pred" ) . withInterval ( decl . sourceInterval ( 556 , 560 ) ) , this . terminal ( "*" ) . withInterval ( decl . sourceInterval ( 561 , 564 ) ) ) . withInterval ( decl . sourceInterval ( 556 , 564 ) ) )
. define ( "Iter_plus" , [ ] , this . seq ( this . app ( "Pred" ) . withInterval ( decl . sourceInterval ( 580 , 584 ) ) , this . terminal ( "+" ) . withInterval ( decl . sourceInterval ( 585 , 588 ) ) ) . withInterval ( decl . sourceInterval ( 580 , 588 ) ) )
. define ( "Iter_opt" , [ ] , this . seq ( this . app ( "Pred" ) . withInterval ( decl . sourceInterval ( 604 , 608 ) ) , this . terminal ( "?" ) . withInterval ( decl . sourceInterval ( 609 , 612 ) ) ) . withInterval ( decl . sourceInterval ( 604 , 612 ) ) )
. define ( "Iter" , [ ] , this . alt ( this . app ( "Iter_star" ) . withInterval ( decl . sourceInterval ( 556 , 564 ) ) , this . app ( "Iter_plus" ) . withInterval ( decl . sourceInterval ( 580 , 588 ) ) , this . app ( "Iter_opt" ) . withInterval ( decl . sourceInterval ( 604 , 612 ) ) , this . app ( "Pred" ) . withInterval ( decl . sourceInterval ( 627 , 631 ) ) ) . withInterval ( decl . sourceInterval ( 556 , 631 ) ) )
. define ( "Pred_not" , [ ] , this . seq ( this . terminal ( "~" ) . withInterval ( decl . sourceInterval ( 646 , 649 ) ) , this . app ( "Lex" ) . withInterval ( decl . sourceInterval ( 650 , 653 ) ) ) . withInterval ( decl . sourceInterval ( 646 , 653 ) ) )
. define ( "Pred_lookahead" , [ ] , this . seq ( this . terminal ( "&" ) . withInterval ( decl . sourceInterval ( 668 , 671 ) ) , this . app ( "Lex" ) . withInterval ( decl . sourceInterval ( 672 , 675 ) ) ) . withInterval ( decl . sourceInterval ( 668 , 675 ) ) )
. define ( "Pred" , [ ] , this . alt ( this . app ( "Pred_not" ) . withInterval ( decl . sourceInterval ( 646 , 653 ) ) , this . app ( "Pred_lookahead" ) . withInterval ( decl . sourceInterval ( 668 , 675 ) ) , this . app ( "Lex" ) . withInterval ( decl . sourceInterval ( 696 , 699 ) ) ) . withInterval ( decl . sourceInterval ( 646 , 699 ) ) )
. define ( "Lex_lex" , [ ] , this . seq ( this . terminal ( "#" ) . withInterval ( decl . sourceInterval ( 713 , 716 ) ) , this . app ( "Base" ) . withInterval ( decl . sourceInterval ( 717 , 721 ) ) ) . withInterval ( decl . sourceInterval ( 713 , 721 ) ) )
. define ( "Lex" , [ ] , this . alt ( this . app ( "Lex_lex" ) . withInterval ( decl . sourceInterval ( 713 , 721 ) ) , this . app ( "Base" ) . withInterval ( decl . sourceInterval ( 736 , 740 ) ) ) . withInterval ( decl . sourceInterval ( 713 , 740 ) ) )
. define ( "Base_application" , [ ] , this . seq ( this . app ( "ident" ) . withInterval ( decl . sourceInterval ( 755 , 760 ) ) , this . opt ( this . app ( "Params" ) . withInterval ( decl . sourceInterval ( 761 , 767 ) ) ) . withInterval ( decl . sourceInterval ( 761 , 768 ) ) , this . not ( this . alt ( this . seq ( this . opt ( this . app ( "ruleDescr" ) . withInterval ( decl . sourceInterval ( 771 , 780 ) ) ) . withInterval ( decl . sourceInterval ( 771 , 781 ) ) , this . terminal ( "=" ) . withInterval ( decl . sourceInterval ( 782 , 785 ) ) ) . withInterval ( decl . sourceInterval ( 771 , 785 ) ) , this . terminal ( ":=" ) . withInterval ( decl . sourceInterval ( 788 , 792 ) ) , this . terminal ( "+=" ) . withInterval ( decl . sourceInterval ( 795 , 799 ) ) ) . withInterval ( decl . sourceInterval ( 771 , 799 ) ) ) . withInterval ( decl . sourceInterval ( 769 , 800 ) ) ) . withInterval ( decl . sourceInterval ( 755 , 800 ) ) )
. define ( "Base_range" , [ ] , this . seq ( this . app ( "terminal" ) . withInterval ( decl . sourceInterval ( 823 , 831 ) ) , this . terminal ( ".." ) . withInterval ( decl . sourceInterval ( 832 , 836 ) ) , this . app ( "terminal" ) . withInterval ( decl . sourceInterval ( 837 , 845 ) ) ) . withInterval ( decl . sourceInterval ( 823 , 845 ) ) )
. define ( "Base_terminal" , [ ] , this . app ( "terminal" ) . withInterval ( decl . sourceInterval ( 885 , 893 ) ) )
. define ( "Base_paren" , [ ] , this . seq ( this . terminal ( "(" ) . withInterval ( decl . sourceInterval ( 950 , 953 ) ) , this . app ( "Alt" ) . withInterval ( decl . sourceInterval ( 954 , 957 ) ) , this . terminal ( ")" ) . withInterval ( decl . sourceInterval ( 958 , 961 ) ) ) . withInterval ( decl . sourceInterval ( 950 , 961 ) ) )
. define ( "Base" , [ ] , this . alt ( this . app ( "Base_application" ) . withInterval ( decl . sourceInterval ( 755 , 800 ) ) , this . app ( "Base_range" ) . withInterval ( decl . sourceInterval ( 823 , 845 ) ) , this . app ( "Base_terminal" ) . withInterval ( decl . sourceInterval ( 885 , 893 ) ) , this . app ( "Base_paren" ) . withInterval ( decl . sourceInterval ( 950 , 961 ) ) ) . withInterval ( decl . sourceInterval ( 755 , 1005 ) ) )
. define ( "ruleDescr" , [ ] , this . seq ( this . terminal ( "(" ) . withInterval ( decl . sourceInterval ( 1047 , 1050 ) ) , this . app ( "ruleDescrText" ) . withInterval ( decl . sourceInterval ( 1051 , 1064 ) ) , this . terminal ( ")" ) . withInterval ( decl . sourceInterval ( 1065 , 1068 ) ) ) . withInterval ( decl . sourceInterval ( 1047 , 1068 ) ) , "a rule description" )
. define ( "ruleDescrText" , [ ] , this . star ( this . seq ( this . not ( this . terminal ( ")" ) . withInterval ( decl . sourceInterval ( 1094 , 1097 ) ) ) . withInterval ( decl . sourceInterval ( 1093 , 1097 ) ) , this . app ( "any" ) . withInterval ( decl . sourceInterval ( 1098 , 1101 ) ) ) . withInterval ( decl . sourceInterval ( 1093 , 1101 ) ) ) . withInterval ( decl . sourceInterval ( 1092 , 1103 ) ) )
. define ( "caseName" , [ ] , this . seq ( this . terminal ( "--" ) . withInterval ( decl . sourceInterval ( 1122 , 1126 ) ) , this . star ( this . seq ( this . not ( this . terminal ( "\n" ) . withInterval ( decl . sourceInterval ( 1129 , 1133 ) ) ) . withInterval ( decl . sourceInterval ( 1128 , 1133 ) ) , this . app ( "space" ) . withInterval ( decl . sourceInterval ( 1134 , 1139 ) ) ) . withInterval ( decl . sourceInterval ( 1128 , 1139 ) ) ) . withInterval ( decl . sourceInterval ( 1127 , 1141 ) ) , this . app ( "name" ) . withInterval ( decl . sourceInterval ( 1142 , 1146 ) ) , this . star ( this . seq ( this . not ( this . terminal ( "\n" ) . withInterval ( decl . sourceInterval ( 1149 , 1153 ) ) ) . withInterval ( decl . sourceInterval ( 1148 , 1153 ) ) , this . app ( "space" ) . withInterval ( decl . sourceInterval ( 1154 , 1159 ) ) ) . withInterval ( decl . sourceInterval ( 1148 , 1159 ) ) ) . withInterval ( decl . sourceInterval ( 1147 , 1161 ) ) , this . alt ( this . terminal ( "\n" ) . withInterval ( decl . sourceInterval ( 1163 , 1167 ) ) , this . la ( this . terminal ( "}" ) . withInterval ( decl . sourceInterval ( 1171 , 1174 ) ) ) . withInterval ( decl . sourceInterval ( 1170 , 1174 ) ) ) . withInterval ( decl . sourceInterval ( 1163 , 1174 ) ) ) . withInterval ( decl . sourceInterval ( 1122 , 1175 ) ) )
. define ( "name" , [ ] , this . seq ( this . app ( "nameFirst" ) . withInterval ( decl . sourceInterval ( 1200 , 1209 ) ) , this . star ( this . app ( "nameRest" ) . withInterval ( decl . sourceInterval ( 1210 , 1218 ) ) ) . withInterval ( decl . sourceInterval ( 1210 , 1219 ) ) ) . withInterval ( decl . sourceInterval ( 1200 , 1219 ) ) , "a name" )
. define ( "nameFirst" , [ ] , this . alt ( this . terminal ( "_" ) . withInterval ( decl . sourceInterval ( 1239 , 1242 ) ) , this . app ( "letter" ) . withInterval ( decl . sourceInterval ( 1249 , 1255 ) ) ) . withInterval ( decl . sourceInterval ( 1239 , 1255 ) ) )
. define ( "nameRest" , [ ] , this . alt ( this . terminal ( "_" ) . withInterval ( decl . sourceInterval ( 1274 , 1277 ) ) , this . app ( "alnum" ) . withInterval ( decl . sourceInterval ( 1284 , 1289 ) ) ) . withInterval ( decl . sourceInterval ( 1274 , 1289 ) ) )
. define ( "ident" , [ ] , this . app ( "name" ) . withInterval ( decl . sourceInterval ( 1322 , 1326 ) ) , "an identifier" )
. define ( "terminal" , [ ] , this . seq ( this . terminal ( "\"" ) . withInterval ( decl . sourceInterval ( 1345 , 1349 ) ) , this . star ( this . app ( "terminalChar" ) . withInterval ( decl . sourceInterval ( 1350 , 1362 ) ) ) . withInterval ( decl . sourceInterval ( 1350 , 1363 ) ) , this . terminal ( "\"" ) . withInterval ( decl . sourceInterval ( 1364 , 1368 ) ) ) . withInterval ( decl . sourceInterval ( 1345 , 1368 ) ) )
. define ( "terminalChar" , [ ] , this . alt ( this . app ( "escapeChar" ) . withInterval ( decl . sourceInterval ( 1391 , 1401 ) ) , this . seq ( this . not ( this . terminal ( "\\" ) . withInterval ( decl . sourceInterval ( 1409 , 1413 ) ) ) . withInterval ( decl . sourceInterval ( 1408 , 1413 ) ) , this . not ( this . terminal ( "\"" ) . withInterval ( decl . sourceInterval ( 1415 , 1419 ) ) ) . withInterval ( decl . sourceInterval ( 1414 , 1419 ) ) , this . not ( this . terminal ( "\n" ) . withInterval ( decl . sourceInterval ( 1421 , 1425 ) ) ) . withInterval ( decl . sourceInterval ( 1420 , 1425 ) ) , this . app ( "any" ) . withInterval ( decl . sourceInterval ( 1426 , 1429 ) ) ) . withInterval ( decl . sourceInterval ( 1408 , 1429 ) ) ) . withInterval ( decl . sourceInterval ( 1391 , 1429 ) ) )
. define ( "escapeChar_backslash" , [ ] , this . terminal ( "\\\\" ) . withInterval ( decl . sourceInterval ( 1472 , 1478 ) ) )
. define ( "escapeChar_doubleQuote" , [ ] , this . terminal ( "\\\"" ) . withInterval ( decl . sourceInterval ( 1534 , 1540 ) ) )
. define ( "escapeChar_singleQuote" , [ ] , this . terminal ( "\\'" ) . withInterval ( decl . sourceInterval ( 1598 , 1604 ) ) )
. define ( "escapeChar_backspace" , [ ] , this . terminal ( "\\b" ) . withInterval ( decl . sourceInterval ( 1662 , 1667 ) ) )
. define ( "escapeChar_lineFeed" , [ ] , this . terminal ( "\\n" ) . withInterval ( decl . sourceInterval ( 1724 , 1729 ) ) )
. define ( "escapeChar_carriageReturn" , [ ] , this . terminal ( "\\r" ) . withInterval ( decl . sourceInterval ( 1785 , 1790 ) ) )
. define ( "escapeChar_tab" , [ ] , this . terminal ( "\\t" ) . withInterval ( decl . sourceInterval ( 1852 , 1857 ) ) )
. define ( "escapeChar_unicodeEscape" , [ ] , this . seq ( this . terminal ( "\\u" ) . withInterval ( decl . sourceInterval ( 1908 , 1913 ) ) , this . app ( "hexDigit" ) . withInterval ( decl . sourceInterval ( 1914 , 1922 ) ) , this . app ( "hexDigit" ) . withInterval ( decl . sourceInterval ( 1923 , 1931 ) ) , this . app ( "hexDigit" ) . withInterval ( decl . sourceInterval ( 1932 , 1940 ) ) , this . app ( "hexDigit" ) . withInterval ( decl . sourceInterval ( 1941 , 1949 ) ) ) . withInterval ( decl . sourceInterval ( 1908 , 1949 ) ) )
. define ( "escapeChar_hexEscape" , [ ] , this . seq ( this . terminal ( "\\x" ) . withInterval ( decl . sourceInterval ( 1974 , 1979 ) ) , this . app ( "hexDigit" ) . withInterval ( decl . sourceInterval ( 1980 , 1988 ) ) , this . app ( "hexDigit" ) . withInterval ( decl . sourceInterval ( 1989 , 1997 ) ) ) . withInterval ( decl . sourceInterval ( 1974 , 1997 ) ) )
. define ( "escapeChar" , [ ] , this . alt ( this . app ( "escapeChar_backslash" ) . withInterval ( decl . sourceInterval ( 1472 , 1478 ) ) , this . app ( "escapeChar_doubleQuote" ) . withInterval ( decl . sourceInterval ( 1534 , 1540 ) ) , this . app ( "escapeChar_singleQuote" ) . withInterval ( decl . sourceInterval ( 1598 , 1604 ) ) , this . app ( "escapeChar_backspace" ) . withInterval ( decl . sourceInterval ( 1662 , 1667 ) ) , this . app ( "escapeChar_lineFeed" ) . withInterval ( decl . sourceInterval ( 1724 , 1729 ) ) , this . app ( "escapeChar_carriageReturn" ) . withInterval ( decl . sourceInterval ( 1785 , 1790 ) ) , this . app ( "escapeChar_tab" ) . withInterval ( decl . sourceInterval ( 1852 , 1857 ) ) , this . app ( "escapeChar_unicodeEscape" ) . withInterval ( decl . sourceInterval ( 1908 , 1949 ) ) , this . app ( "escapeChar_hexEscape" ) . withInterval ( decl . sourceInterval ( 1974 , 1997 ) ) ) . withInterval ( decl . sourceInterval ( 1472 , 2029 ) ) , "an escape sequence" )
. extend ( "space" , [ ] , this . app ( "comment" ) . withInterval ( decl . sourceInterval ( 2045 , 2052 ) ) )
. define ( "comment_singleLine" , [ ] , this . seq ( this . terminal ( "//" ) . withInterval ( decl . sourceInterval ( 2070 , 2074 ) ) , this . star ( this . seq ( this . not ( this . terminal ( "\n" ) . withInterval ( decl . sourceInterval ( 2077 , 2081 ) ) ) . withInterval ( decl . sourceInterval ( 2076 , 2081 ) ) , this . app ( "any" ) . withInterval ( decl . sourceInterval ( 2082 , 2085 ) ) ) . withInterval ( decl . sourceInterval ( 2076 , 2085 ) ) ) . withInterval ( decl . sourceInterval ( 2075 , 2087 ) ) , this . terminal ( "\n" ) . withInterval ( decl . sourceInterval ( 2088 , 2092 ) ) ) . withInterval ( decl . sourceInterval ( 2070 , 2092 ) ) )
. define ( "comment_multiLine" , [ ] , this . seq ( this . terminal ( "/*" ) . withInterval ( decl . sourceInterval ( 2114 , 2118 ) ) , this . star ( this . seq ( this . not ( this . terminal ( "*/" ) . withInterval ( decl . sourceInterval ( 2121 , 2125 ) ) ) . withInterval ( decl . sourceInterval ( 2120 , 2125 ) ) , this . app ( "any" ) . withInterval ( decl . sourceInterval ( 2126 , 2129 ) ) ) . withInterval ( decl . sourceInterval ( 2120 , 2129 ) ) ) . withInterval ( decl . sourceInterval ( 2119 , 2131 ) ) , this . terminal ( "*/" ) . withInterval ( decl . sourceInterval ( 2132 , 2136 ) ) ) . withInterval ( decl . sourceInterval ( 2114 , 2136 ) ) )
. define ( "comment" , [ ] , this . alt ( this . app ( "comment_singleLine" ) . withInterval ( decl . sourceInterval ( 2070 , 2092 ) ) , this . app ( "comment_multiLine" ) . withInterval ( decl . sourceInterval ( 2114 , 2136 ) ) ) . withInterval ( decl . sourceInterval ( 2070 , 2150 ) ) )
. define ( "tokens" , [ ] , this . star ( this . app ( "token" ) . withInterval ( decl . sourceInterval ( 2163 , 2168 ) ) ) . withInterval ( decl . sourceInterval ( 2163 , 2169 ) ) )
. define ( "token" , [ ] , this . alt ( this . app ( "caseName" ) . withInterval ( decl . sourceInterval ( 2181 , 2189 ) ) , this . app ( "comment" ) . withInterval ( decl . sourceInterval ( 2192 , 2199 ) ) , this . app ( "ident" ) . withInterval ( decl . sourceInterval ( 2202 , 2207 ) ) , this . app ( "operator" ) . withInterval ( decl . sourceInterval ( 2210 , 2218 ) ) , this . app ( "punctuation" ) . withInterval ( decl . sourceInterval ( 2221 , 2232 ) ) , this . app ( "terminal" ) . withInterval ( decl . sourceInterval ( 2235 , 2243 ) ) , this . app ( "any" ) . withInterval ( decl . sourceInterval ( 2246 , 2249 ) ) ) . withInterval ( decl . sourceInterval ( 2181 , 2249 ) ) )
. define ( "operator" , [ ] , this . alt ( this . terminal ( "<:" ) . withInterval ( decl . sourceInterval ( 2264 , 2268 ) ) , this . terminal ( "=" ) . withInterval ( decl . sourceInterval ( 2271 , 2274 ) ) , this . terminal ( ":=" ) . withInterval ( decl . sourceInterval ( 2277 , 2281 ) ) , this . terminal ( "+=" ) . withInterval ( decl . sourceInterval ( 2284 , 2288 ) ) , this . terminal ( "*" ) . withInterval ( decl . sourceInterval ( 2291 , 2294 ) ) , this . terminal ( "+" ) . withInterval ( decl . sourceInterval ( 2297 , 2300 ) ) , this . terminal ( "?" ) . withInterval ( decl . sourceInterval ( 2303 , 2306 ) ) , this . terminal ( "~" ) . withInterval ( decl . sourceInterval ( 2309 , 2312 ) ) , this . terminal ( "&" ) . withInterval ( decl . sourceInterval ( 2315 , 2318 ) ) ) . withInterval ( decl . sourceInterval ( 2264 , 2318 ) ) )
. define ( "punctuation" , [ ] , this . alt ( this . terminal ( "<" ) . withInterval ( decl . sourceInterval ( 2336 , 2339 ) ) , this . terminal ( ">" ) . withInterval ( decl . sourceInterval ( 2342 , 2345 ) ) , this . terminal ( "," ) . withInterval ( decl . sourceInterval ( 2348 , 2351 ) ) , this . terminal ( "--" ) . withInterval ( decl . sourceInterval ( 2354 , 2358 ) ) ) . withInterval ( decl . sourceInterval ( 2336 , 2358 ) ) )
. build ( ) ;
} ) ;
2016-04-06 16:22:30 +00:00
} , { ".." : 50 } ] , 12 : [ function ( require , module , exports ) {
var ohm = require ( '..' ) ;
2016-08-07 19:41:10 +00:00
module . exports = ohm . makeRecipe ( function ( ) {
var decl = this . newGrammar ( "OperationsAndAttributes" )
. withSource ( "OperationsAndAttributes {\n\n AttributeSignature =\n name\n\n OperationSignature =\n name Formals?\n\n Formals\n = \"(\" ListOf<name, \",\"> \")\"\n\n name (a name)\n = nameFirst nameRest*\n\n nameFirst\n = \"_\"\n | letter\n\n nameRest\n = \"_\"\n | alnum\n\n}" )
. withDefaultStartRule ( "AttributeSignature" )
return decl
. define ( "AttributeSignature" , [ ] , this . app ( "name" ) . withInterval ( decl . sourceInterval ( 54 , 58 ) ) )
. define ( "OperationSignature" , [ ] , this . seq ( this . app ( "name" ) . withInterval ( decl . sourceInterval ( 87 , 91 ) ) , this . opt ( this . app ( "Formals" ) . withInterval ( decl . sourceInterval ( 92 , 99 ) ) ) . withInterval ( decl . sourceInterval ( 92 , 100 ) ) ) . withInterval ( decl . sourceInterval ( 87 , 100 ) ) )
. define ( "Formals" , [ ] , this . seq ( this . terminal ( "(" ) . withInterval ( decl . sourceInterval ( 118 , 121 ) ) , this . app ( "ListOf" , [ this . app ( "name" ) . withInterval ( decl . sourceInterval ( 129 , 133 ) ) , this . terminal ( "," ) . withInterval ( decl . sourceInterval ( 135 , 138 ) ) ] ) . withInterval ( decl . sourceInterval ( 122 , 139 ) ) , this . terminal ( ")" ) . withInterval ( decl . sourceInterval ( 140 , 143 ) ) ) . withInterval ( decl . sourceInterval ( 118 , 143 ) ) )
. define ( "name" , [ ] , this . seq ( this . app ( "nameFirst" ) . withInterval ( decl . sourceInterval ( 168 , 177 ) ) , this . star ( this . app ( "nameRest" ) . withInterval ( decl . sourceInterval ( 178 , 186 ) ) ) . withInterval ( decl . sourceInterval ( 178 , 187 ) ) ) . withInterval ( decl . sourceInterval ( 168 , 187 ) ) , "a name" )
. define ( "nameFirst" , [ ] , this . alt ( this . terminal ( "_" ) . withInterval ( decl . sourceInterval ( 207 , 210 ) ) , this . app ( "letter" ) . withInterval ( decl . sourceInterval ( 217 , 223 ) ) ) . withInterval ( decl . sourceInterval ( 207 , 223 ) ) )
. define ( "nameRest" , [ ] , this . alt ( this . terminal ( "_" ) . withInterval ( decl . sourceInterval ( 242 , 245 ) ) , this . app ( "alnum" ) . withInterval ( decl . sourceInterval ( 252 , 257 ) ) ) . withInterval ( decl . sourceInterval ( 242 , 257 ) ) )
. build ( ) ;
} ) ;
2016-05-02 21:15:05 +00:00
2016-04-06 16:22:30 +00:00
} , { ".." : 50 } ] , 13 : [ function ( require , module , exports ) {
'use strict' ;
module . exports = {
toAST : require ( './semantics-toAST' ) . helper ,
semanticsForToAST : require ( './semantics-toAST' ) . semantics
} ;
} , { "./semantics-toAST" : 14 } ] , 14 : [ function ( require , module , exports ) {
'use strict' ;
// --------------------------------------------------------------------
// Imports
// --------------------------------------------------------------------
var pexprs = require ( '../src/pexprs' ) ;
var MatchResult = require ( '../src/MatchResult' ) ;
var Grammar = require ( '../src/Grammar' ) ;
var extend = require ( 'util-extend' ) ;
// --------------------------------------------------------------------
// Operations
// --------------------------------------------------------------------
var defaultOperation = {
2016-05-02 21:15:05 +00:00
_terminal : function ( ) {
return this . primitiveValue ;
} ,
2016-04-06 16:22:30 +00:00
_nonterminal : function ( children ) {
var ctorName = this . _node . ctorName ;
var mapping = this . args . mapping ;
// without customization
if ( ! mapping . hasOwnProperty ( ctorName ) ) {
// intermediate node
if ( this . _node instanceof pexprs . Alt || this . _node instanceof pexprs . Apply ) {
return children [ 0 ] . toAST ( mapping ) ;
}
// lexical rule
if ( this . isLexical ( ) ) {
return this . interval . contents ;
}
// singular node (e.g. only surrounded by literals or lookaheads)
var realChildren = children . filter ( function ( child ) {
return ! child . isTerminal ( ) ;
} ) ;
if ( realChildren . length === 1 ) {
return realChildren [ 0 ] . toAST ( mapping ) ;
}
// rest: terms with multiple children
}
// direct forward
if ( typeof mapping [ ctorName ] === 'number' ) {
return children [ mapping [ ctorName ] ] . toAST ( mapping ) ;
}
// named/mapped children or unnamed children ('0', '1', '2', ...)
var propMap = mapping [ ctorName ] || children ;
var node = {
type : ctorName
} ;
for ( var prop in propMap ) {
var mappedProp = mapping [ ctorName ] && mapping [ ctorName ] [ prop ] ;
if ( typeof mappedProp === 'number' ) {
// direct forward
node [ prop ] = children [ mappedProp ] . toAST ( mapping ) ;
} else if ( ( typeof mappedProp === 'string' ) || ( typeof mappedProp === 'boolean' ) ||
( mappedProp === null ) ) {
// primitive value
node [ prop ] = mappedProp ;
} else if ( ( typeof mappedProp === 'object' ) && ( mappedProp instanceof Number ) ) {
// primitive number (must be unboxed)
node [ prop ] = Number ( mappedProp ) ;
} else if ( typeof mappedProp === 'function' ) {
// computed value
node [ prop ] = mappedProp . call ( this , children ) ;
} else if ( mappedProp === undefined ) {
if ( children [ prop ] && ! children [ prop ] . isTerminal ( ) ) {
node [ prop ] = children [ prop ] . toAST ( mapping ) ;
} else {
// delete predefined 'type' properties, like 'type', if explicitely removed
delete node [ prop ] ;
}
}
}
return node ;
} ,
_iter : function ( children ) {
if ( this . _node . isOptional ( ) ) {
if ( this . numChildren === 0 ) {
return null ;
} else {
return children [ 0 ] . toAST ( this . args . mapping ) ;
}
}
return children . map ( function ( child ) {
return child . toAST ( this . args . mapping ) ;
} , this ) ;
} ,
NonemptyListOf : function ( first , sep , rest ) {
return [ first . toAST ( this . args . mapping ) ] . concat ( rest . toAST ( this . args . mapping ) ) ;
} ,
EmptyListOf : function ( ) {
return [ ] ;
}
} ;
// Returns a plain JavaScript object that includes an abstract syntax tree (AST)
// for the given match result `res` containg a concrete syntax tree (CST) and grammar.
// The optional `mapping` parameter can be used to customize how the nodes of the CST
// are mapped to the AST (see /doc/extras.md#toastmatchresult-mapping).
function toAST ( res , mapping ) {
if ( ! ( res instanceof MatchResult ) || res . failed ( ) ) {
throw new Error ( 'toAST() expects a succesfull MatchResult as first parameter' ) ;
}
mapping = extend ( { } , mapping ) ;
var operation = extend ( { } , defaultOperation ) ;
for ( var termName in mapping ) {
if ( typeof mapping [ termName ] === 'function' ) {
operation [ termName ] = mapping [ termName ] ;
delete mapping [ termName ] ;
}
}
var g = res . _cst . grammar ;
var s = g . semantics ( ) . addOperation ( 'toAST(mapping)' , operation ) ;
return s ( res ) . toAST ( mapping ) ;
}
// Returns a semantics containg the toAST(mapping) operation for the given grammar g.
function semanticsForToAST ( g ) {
if ( ! ( g instanceof Grammar ) ) {
throw new Error ( 'semanticsToAST() expects a Grammar as parameter' ) ;
}
return g . semantics ( ) . addOperation ( 'toAST(mapping)' , defaultOperation ) ;
}
module . exports = {
helper : toAST ,
semantics : semanticsForToAST
} ;
2016-05-16 17:27:46 +00:00
} , { "../src/Grammar" : 38 , "../src/MatchResult" : 42 , "../src/pexprs" : 67 , "util-extend" : 35 } ] , 15 : [ function ( require , module , exports ) {
2016-04-06 16:22:30 +00:00
'use strict' ;
module . exports = require ( './is-implemented' ) ( ) ? Symbol : require ( './polyfill' ) ;
} , { "./is-implemented" : 16 , "./polyfill" : 31 } ] , 16 : [ function ( require , module , exports ) {
'use strict' ;
module . exports = function ( ) {
var symbol ;
if ( typeof Symbol !== 'function' ) return false ;
symbol = Symbol ( 'test symbol' ) ;
try { String ( symbol ) ; } catch ( e ) { return false ; }
if ( typeof Symbol . iterator === 'symbol' ) return true ;
// Return 'true' for polyfills
if ( typeof Symbol . isConcatSpreadable !== 'object' ) return false ;
if ( typeof Symbol . iterator !== 'object' ) return false ;
if ( typeof Symbol . toPrimitive !== 'object' ) return false ;
if ( typeof Symbol . toStringTag !== 'object' ) return false ;
if ( typeof Symbol . unscopables !== 'object' ) return false ;
return true ;
} ;
} , { } ] , 17 : [ function ( require , module , exports ) {
'use strict' ;
module . exports = function ( x ) {
return ( x && ( ( typeof x === 'symbol' ) || ( x [ '@@toStringTag' ] === 'Symbol' ) ) ) || false ;
} ;
} , { } ] , 18 : [ function ( require , module , exports ) {
'use strict' ;
var assign = require ( 'es5-ext/object/assign' )
, normalizeOpts = require ( 'es5-ext/object/normalize-options' )
, isCallable = require ( 'es5-ext/object/is-callable' )
, contains = require ( 'es5-ext/string/#/contains' )
, d ;
d = module . exports = function ( dscr , value /*, options*/ ) {
var c , e , w , options , desc ;
if ( ( arguments . length < 2 ) || ( typeof dscr !== 'string' ) ) {
options = value ;
value = dscr ;
dscr = null ;
} else {
options = arguments [ 2 ] ;
}
if ( dscr == null ) {
c = w = true ;
e = false ;
} else {
c = contains . call ( dscr , 'c' ) ;
e = contains . call ( dscr , 'e' ) ;
w = contains . call ( dscr , 'w' ) ;
}
desc = { value : value , configurable : c , enumerable : e , writable : w } ;
return ! options ? desc : assign ( normalizeOpts ( options ) , desc ) ;
} ;
d . gs = function ( dscr , get , set /*, options*/ ) {
var c , e , options , desc ;
if ( typeof dscr !== 'string' ) {
options = set ;
set = get ;
get = dscr ;
dscr = null ;
} else {
options = arguments [ 3 ] ;
}
if ( get == null ) {
get = undefined ;
} else if ( ! isCallable ( get ) ) {
options = get ;
get = set = undefined ;
} else if ( set == null ) {
set = undefined ;
} else if ( ! isCallable ( set ) ) {
options = set ;
set = undefined ;
}
if ( dscr == null ) {
c = true ;
e = false ;
} else {
c = contains . call ( dscr , 'c' ) ;
e = contains . call ( dscr , 'e' ) ;
}
desc = { get : get , set : set , configurable : c , enumerable : e } ;
return ! options ? desc : assign ( normalizeOpts ( options ) , desc ) ;
} ;
} , { "es5-ext/object/assign" : 19 , "es5-ext/object/is-callable" : 22 , "es5-ext/object/normalize-options" : 26 , "es5-ext/string/#/contains" : 28 } ] , 19 : [ function ( require , module , exports ) {
'use strict' ;
module . exports = require ( './is-implemented' ) ( )
? Object . assign
: require ( './shim' ) ;
} , { "./is-implemented" : 20 , "./shim" : 21 } ] , 20 : [ function ( require , module , exports ) {
'use strict' ;
module . exports = function ( ) {
var assign = Object . assign , obj ;
if ( typeof assign !== 'function' ) return false ;
obj = { foo : 'raz' } ;
assign ( obj , { bar : 'dwa' } , { trzy : 'trzy' } ) ;
return ( obj . foo + obj . bar + obj . trzy ) === 'razdwatrzy' ;
} ;
} , { } ] , 21 : [ function ( require , module , exports ) {
'use strict' ;
var keys = require ( '../keys' )
, value = require ( '../valid-value' )
, max = Math . max ;
module . exports = function ( dest , src /*, …srcn*/ ) {
var error , i , l = max ( arguments . length , 2 ) , assign ;
dest = Object ( value ( dest ) ) ;
assign = function ( key ) {
try { dest [ key ] = src [ key ] ; } catch ( e ) {
if ( ! error ) error = e ;
}
} ;
for ( i = 1 ; i < l ; ++ i ) {
src = arguments [ i ] ;
keys ( src ) . forEach ( assign ) ;
}
if ( error !== undefined ) throw error ;
return dest ;
} ;
} , { "../keys" : 23 , "../valid-value" : 27 } ] , 22 : [ function ( require , module , exports ) {
// Deprecated
'use strict' ;
module . exports = function ( obj ) { return typeof obj === 'function' ; } ;
} , { } ] , 23 : [ function ( require , module , exports ) {
'use strict' ;
module . exports = require ( './is-implemented' ) ( )
? Object . keys
: require ( './shim' ) ;
} , { "./is-implemented" : 24 , "./shim" : 25 } ] , 24 : [ function ( require , module , exports ) {
'use strict' ;
module . exports = function ( ) {
try {
Object . keys ( 'primitive' ) ;
return true ;
} catch ( e ) { return false ; }
} ;
} , { } ] , 25 : [ function ( require , module , exports ) {
'use strict' ;
var keys = Object . keys ;
module . exports = function ( object ) {
return keys ( object == null ? object : Object ( object ) ) ;
} ;
} , { } ] , 26 : [ function ( require , module , exports ) {
'use strict' ;
var forEach = Array . prototype . forEach , create = Object . create ;
var process = function ( src , obj ) {
var key ;
for ( key in src ) obj [ key ] = src [ key ] ;
} ;
module . exports = function ( options /*, …options*/ ) {
var result = create ( null ) ;
forEach . call ( arguments , function ( options ) {
if ( options == null ) return ;
process ( Object ( options ) , result ) ;
} ) ;
return result ;
} ;
} , { } ] , 27 : [ function ( require , module , exports ) {
'use strict' ;
module . exports = function ( value ) {
if ( value == null ) throw new TypeError ( "Cannot use null or undefined" ) ;
return value ;
} ;
} , { } ] , 28 : [ function ( require , module , exports ) {
'use strict' ;
module . exports = require ( './is-implemented' ) ( )
? String . prototype . contains
: require ( './shim' ) ;
} , { "./is-implemented" : 29 , "./shim" : 30 } ] , 29 : [ function ( require , module , exports ) {
'use strict' ;
var str = 'razdwatrzy' ;
module . exports = function ( ) {
if ( typeof str . contains !== 'function' ) return false ;
return ( ( str . contains ( 'dwa' ) === true ) && ( str . contains ( 'foo' ) === false ) ) ;
} ;
} , { } ] , 30 : [ function ( require , module , exports ) {
'use strict' ;
var indexOf = String . prototype . indexOf ;
module . exports = function ( searchString /*, position*/ ) {
return indexOf . call ( this , searchString , arguments [ 1 ] ) > - 1 ;
} ;
} , { } ] , 31 : [ function ( require , module , exports ) {
'use strict' ;
var d = require ( 'd' )
, validateSymbol = require ( './validate-symbol' )
, create = Object . create , defineProperties = Object . defineProperties
, defineProperty = Object . defineProperty , objPrototype = Object . prototype
, Symbol , HiddenSymbol , globalSymbols = create ( null ) ;
var generateName = ( function ( ) {
var created = create ( null ) ;
return function ( desc ) {
var postfix = 0 , name ;
while ( created [ desc + ( postfix || '' ) ] ) ++ postfix ;
desc += ( postfix || '' ) ;
created [ desc ] = true ;
name = '@@' + desc ;
defineProperty ( objPrototype , name , d . gs ( null , function ( value ) {
defineProperty ( this , name , d ( value ) ) ;
} ) ) ;
return name ;
} ;
} ( ) ) ;
HiddenSymbol = function Symbol ( description ) {
if ( this instanceof HiddenSymbol ) throw new TypeError ( 'TypeError: Symbol is not a constructor' ) ;
return Symbol ( description ) ;
} ;
module . exports = Symbol = function Symbol ( description ) {
var symbol ;
if ( this instanceof Symbol ) throw new TypeError ( 'TypeError: Symbol is not a constructor' ) ;
symbol = create ( HiddenSymbol . prototype ) ;
description = ( description === undefined ? '' : String ( description ) ) ;
return defineProperties ( symbol , {
_ _description _ _ : d ( '' , description ) ,
_ _name _ _ : d ( '' , generateName ( description ) )
} ) ;
} ;
defineProperties ( Symbol , {
for : d ( function ( key ) {
if ( globalSymbols [ key ] ) return globalSymbols [ key ] ;
return ( globalSymbols [ key ] = Symbol ( String ( key ) ) ) ;
} ) ,
keyFor : d ( function ( s ) {
var key ;
validateSymbol ( s ) ;
for ( key in globalSymbols ) if ( globalSymbols [ key ] === s ) return key ;
} ) ,
hasInstance : d ( '' , Symbol ( 'hasInstance' ) ) ,
isConcatSpreadable : d ( '' , Symbol ( 'isConcatSpreadable' ) ) ,
iterator : d ( '' , Symbol ( 'iterator' ) ) ,
match : d ( '' , Symbol ( 'match' ) ) ,
replace : d ( '' , Symbol ( 'replace' ) ) ,
search : d ( '' , Symbol ( 'search' ) ) ,
species : d ( '' , Symbol ( 'species' ) ) ,
split : d ( '' , Symbol ( 'split' ) ) ,
toPrimitive : d ( '' , Symbol ( 'toPrimitive' ) ) ,
toStringTag : d ( '' , Symbol ( 'toStringTag' ) ) ,
unscopables : d ( '' , Symbol ( 'unscopables' ) )
} ) ;
defineProperties ( HiddenSymbol . prototype , {
constructor : d ( Symbol ) ,
toString : d ( '' , function ( ) { return this . _ _name _ _ ; } )
} ) ;
defineProperties ( Symbol . prototype , {
toString : d ( function ( ) { return 'Symbol (' + validateSymbol ( this ) . _ _description _ _ + ')' ; } ) ,
valueOf : d ( function ( ) { return validateSymbol ( this ) ; } )
} ) ;
defineProperty ( Symbol . prototype , Symbol . toPrimitive , d ( '' ,
function ( ) { return validateSymbol ( this ) ; } ) ) ;
defineProperty ( Symbol . prototype , Symbol . toStringTag , d ( 'c' , 'Symbol' ) ) ;
defineProperty ( HiddenSymbol . prototype , Symbol . toPrimitive ,
d ( 'c' , Symbol . prototype [ Symbol . toPrimitive ] ) ) ;
defineProperty ( HiddenSymbol . prototype , Symbol . toStringTag ,
d ( 'c' , Symbol . prototype [ Symbol . toStringTag ] ) ) ;
} , { "./validate-symbol" : 32 , "d" : 18 } ] , 32 : [ function ( require , module , exports ) {
'use strict' ;
var isSymbol = require ( './is-symbol' ) ;
module . exports = function ( value ) {
if ( ! isSymbol ( value ) ) throw new TypeError ( value + " is not a symbol" ) ;
return value ;
} ;
} , { "./is-symbol" : 17 } ] , 33 : [ function ( require , module , exports ) {
if ( typeof Object . create === 'function' ) {
// implementation from standard node.js 'util' module
module . exports = function inherits ( ctor , superCtor ) {
ctor . super _ = superCtor
ctor . prototype = Object . create ( superCtor . prototype , {
constructor : {
value : ctor ,
enumerable : false ,
writable : true ,
configurable : true
}
} ) ;
} ;
} else {
// old school shim for old browsers
module . exports = function inherits ( ctor , superCtor ) {
ctor . super _ = superCtor
var TempCtor = function ( ) { }
TempCtor . prototype = superCtor . prototype
ctor . prototype = new TempCtor ( )
ctor . prototype . constructor = ctor
}
}
} , { } ] , 34 : [ function ( require , module , exports ) {
/ * *
* Determine if an object is Buffer
*
* Author : Feross Aboukhadijeh < feross @ feross . org > < http : //feross.org>
* License : MIT
*
* ` npm install is-buffer `
* /
module . exports = function ( obj ) {
return ! ! (
obj != null &&
obj . constructor &&
typeof obj . constructor . isBuffer === 'function' &&
obj . constructor . isBuffer ( obj )
)
}
} , { } ] , 35 : [ function ( require , module , exports ) {
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
module . exports = extend ;
function extend ( origin , add ) {
// Don't do anything if add isn't an object
if ( ! add || typeof add !== 'object' ) return origin ;
var keys = Object . keys ( add ) ;
var i = keys . length ;
while ( i -- ) {
origin [ keys [ i ] ] = add [ keys [ i ] ] ;
}
return origin ;
}
} , { } ] , 36 : [ function ( require , module , exports ) {
'use strict' ;
// --------------------------------------------------------------------
// Imports
// --------------------------------------------------------------------
var GrammarDecl = require ( './GrammarDecl' ) ;
var pexprs = require ( './pexprs' ) ;
// --------------------------------------------------------------------
// Private stuff
// --------------------------------------------------------------------
function Builder ( ) { }
Builder . prototype = {
newGrammar : function ( name ) {
return new GrammarDecl ( name ) ;
} ,
2016-05-16 17:27:46 +00:00
terminal : function ( x ) {
return new pexprs . Terminal ( x ) ;
2016-04-06 16:22:30 +00:00
} ,
range : function ( from , to ) {
return new pexprs . Range ( from , to ) ;
} ,
param : function ( index ) {
return new pexprs . Param ( index ) ;
} ,
alt : function ( /* term1, term1, ... */ ) {
var terms = [ ] ;
for ( var idx = 0 ; idx < arguments . length ; idx ++ ) {
var arg = arguments [ idx ] ;
if ( arg instanceof pexprs . Alt ) {
terms = terms . concat ( arg . terms ) ;
} else {
terms . push ( arg ) ;
}
}
return terms . length === 1 ? terms [ 0 ] : new pexprs . Alt ( terms ) ;
} ,
seq : function ( /* factor1, factor2, ... */ ) {
var factors = [ ] ;
for ( var idx = 0 ; idx < arguments . length ; idx ++ ) {
var arg = arguments [ idx ] ;
if ( arg instanceof pexprs . Seq ) {
factors = factors . concat ( arg . factors ) ;
} else {
factors . push ( arg ) ;
}
}
return factors . length === 1 ? factors [ 0 ] : new pexprs . Seq ( factors ) ;
} ,
star : function ( expr ) {
return new pexprs . Star ( expr ) ;
} ,
plus : function ( expr ) {
return new pexprs . Plus ( expr ) ;
} ,
opt : function ( expr ) {
return new pexprs . Opt ( expr ) ;
} ,
not : function ( expr ) {
return new pexprs . Not ( expr ) ;
} ,
la : function ( expr ) {
return new pexprs . Lookahead ( expr ) ;
} ,
lex : function ( expr ) {
return new pexprs . Lex ( expr ) ;
} ,
app : function ( ruleName , optParams ) {
return new pexprs . Apply ( ruleName , optParams ) ;
}
} ;
// --------------------------------------------------------------------
// Exports
// --------------------------------------------------------------------
module . exports = Builder ;
2016-08-07 19:41:10 +00:00
} , { "./GrammarDecl" : 39 , "./pexprs" : 67 } ] , 37 : [ function ( require , module , exports ) {
2016-04-06 16:22:30 +00:00
'use strict' ;
// --------------------------------------------------------------------
// Private stuff
// --------------------------------------------------------------------
/ *
` Failure ` s represent expressions that weren ' t matched while parsing . They are used to generate
error messages automatically . The interface of ` Failure ` s includes the collowing methods :
- getText ( ) : String
- getType ( ) : String ( one of { "description" , "string" , "code" } )
- isDescription ( ) : bool
- isStringTerminal ( ) : bool
- isCode ( ) : bool
- isFluffy ( ) : bool
- makeFluffy ( ) : void
- subsumes ( Failure ) : bool
* /
function isValidType ( type ) {
return type === 'description' || type === 'string' || type === 'code' ;
}
2016-08-07 19:41:10 +00:00
function Failure ( text , type ) {
2016-04-06 16:22:30 +00:00
if ( ! isValidType ( type ) ) {
throw new Error ( 'invalid Failure type: ' + type ) ;
}
2016-08-07 19:41:10 +00:00
2016-04-06 16:22:30 +00:00
this . text = text ;
this . type = type ;
this . fluffy = false ;
}
Failure . prototype . getText = function ( ) {
return this . text ;
} ;
Failure . prototype . getType = function ( ) {
return this . type ;
} ;
Failure . prototype . isDescription = function ( ) {
return this . type === 'description' ;
} ;
Failure . prototype . isStringTerminal = function ( ) {
return this . type === 'string' ;
} ;
Failure . prototype . isCode = function ( ) {
return this . type === 'code' ;
} ;
Failure . prototype . isFluffy = function ( ) {
return this . fluffy ;
} ;
Failure . prototype . makeFluffy = function ( ) {
this . fluffy = true ;
} ;
Failure . prototype . clearFluffy = function ( ) {
this . fluffy = false ;
} ;
Failure . prototype . subsumes = function ( that ) {
return this . getText ( ) === that . getText ( ) &&
this . type === that . type &&
( ! this . isFluffy ( ) || this . isFluffy ( ) && that . isFluffy ( ) ) ;
} ;
Failure . prototype . toString = function ( ) {
return this . type === 'string' ?
JSON . stringify ( this . getText ( ) ) :
this . getText ( ) ;
} ;
Failure . prototype . clone = function ( ) {
2016-08-07 19:41:10 +00:00
var failure = new Failure ( this . text , this . type ) ;
2016-04-06 16:22:30 +00:00
if ( this . isFluffy ( ) ) {
failure . makeFluffy ( ) ;
}
return failure ;
} ;
Failure . prototype . toKey = function ( ) {
return this . toString ( ) + '#' + this . type ;
} ;
// --------------------------------------------------------------------
// Exports
// --------------------------------------------------------------------
module . exports = Failure ;
} , { } ] , 38 : [ function ( require , module , exports ) {
'use strict' ;
// --------------------------------------------------------------------
// Imports
// --------------------------------------------------------------------
var MatchResult = require ( './MatchResult' ) ;
var Semantics = require ( './Semantics' ) ;
var State = require ( './State' ) ;
var common = require ( './common' ) ;
var errors = require ( './errors' ) ;
var pexprs = require ( './pexprs' ) ;
// --------------------------------------------------------------------
// Private stuff
// --------------------------------------------------------------------
function Grammar (
name ,
superGrammar ,
ruleBodies ,
ruleFormals ,
ruleDescriptions ,
optDefaultStartRule ) {
this . name = name ;
this . superGrammar = superGrammar ;
this . ruleBodies = ruleBodies ;
this . ruleFormals = ruleFormals ;
this . ruleDescriptions = ruleDescriptions ;
if ( optDefaultStartRule ) {
if ( ! ( optDefaultStartRule in ruleBodies ) ) {
throw new Error ( "Invalid start rule: '" + optDefaultStartRule +
"' is not a rule in grammar '" + name + "'" ) ;
}
this . defaultStartRule = optDefaultStartRule ;
}
}
var ohmGrammar ;
var buildGrammar ;
// This method is called from main.js once Ohm has loaded.
2016-05-02 21:15:05 +00:00
Grammar . initApplicationParser = function ( grammar , builderFn ) {
2016-04-06 16:22:30 +00:00
ohmGrammar = grammar ;
buildGrammar = builderFn ;
} ;
Grammar . prototype = {
// Return true if the grammar is a built-in grammar, otherwise false.
// NOTE: This might give an unexpected result if called before BuiltInRules is defined!
isBuiltIn : function ( ) {
return this === Grammar . ProtoBuiltInRules || this === Grammar . BuiltInRules ;
} ,
2016-05-16 17:27:46 +00:00
_match : function ( input , opts ) {
var state = new State ( this , input , opts ) ;
2016-05-02 21:15:05 +00:00
state . evalFromStart ( ) ;
return state ;
2016-04-06 16:22:30 +00:00
} ,
2016-05-16 17:27:46 +00:00
match : function ( input , optStartApplication ) {
var state = this . _match ( input , { startApplication : optStartApplication } ) ;
2016-05-02 21:15:05 +00:00
return MatchResult . newFor ( state ) ;
2016-04-06 16:22:30 +00:00
} ,
2016-05-16 17:27:46 +00:00
trace : function ( input , optStartApplication ) {
var state = this . _match ( input , { startApplication : optStartApplication , trace : true } ) ;
2016-04-06 16:22:30 +00:00
2016-05-02 21:15:05 +00:00
// The trace node for the start rule is always the last entry. If it is a syntactic rule,
// the first entry is for an application of 'spaces'.
// TODO(pdubroy): Clean this up by introducing a special `Match<startAppl>` rule, which will
// ensure that there is always a single root trace node.
var rootTrace = state . trace [ state . trace . length - 1 ] ;
2016-04-06 16:22:30 +00:00
rootTrace . state = state ;
rootTrace . result = MatchResult . newFor ( state ) ;
return rootTrace ;
} ,
semantics : function ( ) {
return Semantics . createSemantics ( this ) ;
} ,
extendSemantics : function ( superSemantics ) {
return Semantics . createSemantics ( this , superSemantics . _getSemantics ( ) ) ;
} ,
// Check that every key in `actionDict` corresponds to a semantic action, and that it maps to
// a function of the correct arity. If not, throw an exception.
_checkTopDownActionDict : function ( what , name , actionDict ) {
function isSpecialAction ( a ) {
return a === '_iter' || a === '_terminal' || a === '_nonterminal' || a === '_default' ;
}
var problems = [ ] ;
for ( var k in actionDict ) {
var v = actionDict [ k ] ;
if ( ! isSpecialAction ( k ) && ! ( k in this . ruleBodies ) ) {
problems . push ( "'" + k + "' is not a valid semantic action for '" + this . name + "'" ) ;
} else if ( typeof v !== 'function' ) {
problems . push (
"'" + k + "' must be a function in an action dictionary for '" + this . name + "'" ) ;
} else {
var actual = v . length ;
var expected = this . _topDownActionArity ( k ) ;
if ( actual !== expected ) {
problems . push (
"Semantic action '" + k + "' has the wrong arity: " +
'expected ' + expected + ', got ' + actual ) ;
}
}
}
if ( problems . length > 0 ) {
var prettyProblems = problems . map ( function ( problem ) { return '- ' + problem ; } ) ;
var error = new Error (
"Found errors in the action dictionary of the '" + name + "' " + what + ':\n' +
prettyProblems . join ( '\n' ) ) ;
error . problems = problems ;
throw error ;
}
} ,
// Return the expected arity for a semantic action named `actionName`, which
// is either a rule name or a special action name like '_nonterminal'.
_topDownActionArity : function ( actionName ) {
if ( actionName === '_iter' || actionName === '_nonterminal' || actionName === '_default' ) {
return 1 ;
} else if ( actionName === '_terminal' ) {
return 0 ;
}
return this . ruleBodies [ actionName ] . getArity ( ) ;
} ,
_inheritsFrom : function ( grammar ) {
var g = this . superGrammar ;
while ( g ) {
if ( g === grammar ) {
return true ;
}
g = g . superGrammar ;
}
return false ;
} ,
toRecipe : function ( optVarName ) {
2016-08-07 19:41:10 +00:00
if ( this . isBuiltIn ( ) ) {
throw new Error (
'Why would anyone want to generate a recipe for the ' + this . name + ' grammar?!?!' ) ;
}
var sb = new common . StringBuffer ( ) ;
if ( optVarName ) {
sb . append ( 'var ' + optVarName + ' = ' ) ;
2016-04-06 16:22:30 +00:00
}
2016-08-07 19:41:10 +00:00
sb . append ( '(function() {\n' ) ;
2016-04-06 16:22:30 +00:00
2016-08-07 19:41:10 +00:00
// Include the supergrammar in the recipe if it's not a built-in grammar.
var superGrammarDecl = '' ;
if ( ! this . superGrammar . isBuiltIn ( ) ) {
sb . append ( this . superGrammar . toRecipe ( 'buildSuperGrammar' ) ) ;
superGrammarDecl = ' .withSuperGrammar(buildSuperGrammar.call(this))\n' ;
2016-07-11 16:06:07 +00:00
}
2016-08-07 19:41:10 +00:00
sb . append ( ' var decl = this.newGrammar(' + JSON . stringify ( this . name ) + ')\n' ) ;
// Include the grammar source if it is available.
if ( this . definitionInterval ) {
sb . append ( ' .withSource(' + JSON . stringify ( this . definitionInterval . contents ) + ')\n' ) ;
}
sb . append ( superGrammarDecl ) ;
2016-07-11 16:06:07 +00:00
2016-04-06 16:22:30 +00:00
if ( this . defaultStartRule ) {
2016-08-07 19:41:10 +00:00
sb . append ( ' .withDefaultStartRule("' + this . defaultStartRule + '")\n' ) ;
2016-04-06 16:22:30 +00:00
}
2016-08-07 19:41:10 +00:00
sb . append ( ' return decl\n' ) ;
2016-04-06 16:22:30 +00:00
var self = this ;
Object . keys ( this . ruleBodies ) . forEach ( function ( ruleName ) {
var body = self . ruleBodies [ ruleName ] ;
2016-08-07 19:41:10 +00:00
sb . append ( ' .' ) ;
if ( self . superGrammar . ruleBodies [ ruleName ] ) {
sb . append ( body instanceof pexprs . Extend ? 'extend' : 'override' ) ;
2016-04-06 16:22:30 +00:00
} else {
2016-08-07 19:41:10 +00:00
sb . append ( 'define' ) ;
2016-04-06 16:22:30 +00:00
}
2016-08-07 19:41:10 +00:00
var formals = self . ruleFormals [ ruleName ] ;
var formalsString = '[' + formals . map ( JSON . stringify ) . join ( ', ' ) + ']' ;
sb . append ( '(' + JSON . stringify ( ruleName ) + ', ' + formalsString + ', ' ) ;
body . outputRecipe ( sb , formals , self . definitionInterval ) ;
2016-04-06 16:22:30 +00:00
2016-08-07 19:41:10 +00:00
if ( ! self . superGrammar . ruleBodies [ ruleName ] && self . ruleDescriptions [ ruleName ] ) {
sb . append ( ', ' + JSON . stringify ( self . ruleDescriptions [ ruleName ] ) ) ;
2016-04-06 16:22:30 +00:00
}
2016-08-07 19:41:10 +00:00
sb . append ( ')\n' ) ;
2016-04-06 16:22:30 +00:00
} ) ;
2016-08-07 19:41:10 +00:00
sb . append ( ' .build();\n});\n' ) ;
return sb . contents ( ) ;
2016-04-06 16:22:30 +00:00
} ,
// TODO: Come up with better names for these methods.
// TODO: Write the analog of these methods for inherited attributes.
toOperationActionDictionaryTemplate : function ( ) {
return this . _toOperationOrAttributeActionDictionaryTemplate ( ) ;
} ,
toAttributeActionDictionaryTemplate : function ( ) {
return this . _toOperationOrAttributeActionDictionaryTemplate ( ) ;
} ,
_toOperationOrAttributeActionDictionaryTemplate : function ( ) {
// TODO: add the super-grammar's templates at the right place, e.g., a case for AddExpr_plus
// should appear next to other cases of AddExpr.
var sb = new common . StringBuffer ( ) ;
sb . append ( '{' ) ;
var first = true ;
for ( var ruleName in this . ruleBodies ) {
var body = this . ruleBodies [ ruleName ] ;
if ( first ) {
first = false ;
} else {
sb . append ( ',' ) ;
}
sb . append ( '\n' ) ;
sb . append ( ' ' ) ;
this . addSemanticActionTemplate ( ruleName , body , sb ) ;
}
sb . append ( '\n}' ) ;
return sb . contents ( ) ;
} ,
addSemanticActionTemplate : function ( ruleName , body , sb ) {
sb . append ( ruleName ) ;
sb . append ( ': function(' ) ;
var arity = this . _topDownActionArity ( ruleName ) ;
sb . append ( common . repeat ( '_' , arity ) . join ( ', ' ) ) ;
sb . append ( ') {\n' ) ;
sb . append ( ' }' ) ;
2016-05-02 21:15:05 +00:00
} ,
// Parse a string which expresses a rule application in this grammar, and return the
// resulting Apply node.
parseApplication : function ( str ) {
var app ;
if ( str . indexOf ( '<' ) === - 1 ) {
// simple application
app = new pexprs . Apply ( str ) ;
} else {
// parameterized application
var cst = ohmGrammar . match ( str , 'Base_application' ) ;
app = buildGrammar ( cst , { } ) ;
}
// Ensure that the application is valid.
if ( ! ( app . ruleName in this . ruleBodies ) ) {
throw errors . undeclaredRule ( app . ruleName , this . name ) ;
} else if ( this . ruleFormals [ app . ruleName ] . length !== app . args . length ) {
throw errors . wrongNumberOfParameters (
app . ruleName , this . ruleFormals [ app . ruleName ] . length , app . args . length ) ;
}
return app ;
2016-04-06 16:22:30 +00:00
}
} ;
// The following grammar contains a few rules that couldn't be written in "userland".
// At the bottom of src/main.js, we create a sub-grammar of this grammar that's called
// `BuiltInRules`. That grammar contains several convenience rules, e.g., `letter` and
// `digit`, and is implicitly the super-grammar of any grammar whose super-grammar
// isn't specified.
Grammar . ProtoBuiltInRules = new Grammar (
'ProtoBuiltInRules' , // name
undefined , // supergrammar
// rule bodies
{
2016-05-02 21:15:05 +00:00
// The following rules can't be written in userland because they reference
// `any` and `end` directly.
2016-04-06 16:22:30 +00:00
any : pexprs . any ,
end : pexprs . end ,
// The following rule is invoked implicitly by syntactic rules to skip spaces.
spaces : new pexprs . Star ( new pexprs . Apply ( 'space' ) ) ,
// The `space` rule must be defined here because it's referenced by `spaces`.
space : new pexprs . Range ( '\x00' , ' ' ) ,
2016-05-02 21:15:05 +00:00
// These rules are implemented natively because they use UnicodeChar directly, which is
// not part of the Ohm grammar.
lower : new pexprs . UnicodeChar ( 'Ll' ) ,
2016-04-06 16:22:30 +00:00
upper : new pexprs . UnicodeChar ( 'Lu' ) ,
2016-05-02 21:15:05 +00:00
// The union of Lt (titlecase), Lm (modifier), and Lo (other), i.e. any letter not
// in Ll or Lu.
unicodeLtmo : new pexprs . UnicodeChar ( 'Ltmo' )
2016-04-06 16:22:30 +00:00
} ,
// rule formal arguments
{
any : [ ] ,
end : [ ] ,
spaces : [ ] ,
space : [ ] ,
lower : [ ] ,
upper : [ ] ,
2016-05-02 21:15:05 +00:00
unicodeLtmo : [ ]
2016-04-06 16:22:30 +00:00
} ,
// rule descriptions
{
any : 'any object' ,
end : 'end of input' ,
space : 'a space' ,
lower : 'a lowercase letter' ,
upper : 'an uppercase letter'
}
) ;
// --------------------------------------------------------------------
// Exports
// --------------------------------------------------------------------
module . exports = Grammar ;
2016-05-16 17:27:46 +00:00
} , { "./MatchResult" : 42 , "./Semantics" : 45 , "./State" : 46 , "./common" : 48 , "./errors" : 49 , "./pexprs" : 67 } ] , 39 : [ function ( require , module , exports ) {
2016-04-06 16:22:30 +00:00
'use strict' ;
// --------------------------------------------------------------------
// Imports
// --------------------------------------------------------------------
var Grammar = require ( './Grammar' ) ;
var InputStream = require ( './InputStream' ) ;
var common = require ( './common' ) ;
var errors = require ( './errors' ) ;
var pexprs = require ( './pexprs' ) ;
// --------------------------------------------------------------------
// Private Stuff
// --------------------------------------------------------------------
// Constructors
function GrammarDecl ( name ) {
this . name = name ;
}
// Helpers
GrammarDecl . prototype . sourceInterval = function ( startIdx , endIdx ) {
var inputStream = this . interval . inputStream ;
return inputStream . interval ( startIdx , endIdx ) ;
} ;
GrammarDecl . prototype . ensureSuperGrammar = function ( ) {
if ( ! this . superGrammar ) {
this . withSuperGrammar (
// TODO: The conditional expression below is an ugly hack. It's kind of ok because
// I doubt anyone will ever try to declare a grammar called `BuiltInRules`. Still,
// we should try to find a better way to do this.
this . name === 'BuiltInRules' ?
Grammar . ProtoBuiltInRules :
Grammar . BuiltInRules ) ;
}
return this . superGrammar ;
} ;
GrammarDecl . prototype . installOverriddenOrExtendedRule = function ( name , formals , body ) {
var duplicateParameterNames = common . getDuplicates ( formals ) ;
if ( duplicateParameterNames . length > 0 ) {
throw errors . duplicateParameterNames ( name , duplicateParameterNames , body ) ;
}
var expectedFormals = this . ensureSuperGrammar ( ) . ruleFormals [ name ] ;
var expectedNumFormals = expectedFormals ? expectedFormals . length : 0 ;
if ( formals . length !== expectedNumFormals ) {
throw errors . wrongNumberOfParameters ( name , expectedNumFormals , formals . length , body ) ;
}
return this . install ( name , formals , body ) ;
} ;
GrammarDecl . prototype . install = function ( name , formals , body , optDescription ) {
body = body . introduceParams ( formals ) ;
this . ruleFormals [ name ] = formals ;
if ( optDescription ) {
this . ruleDescriptions [ name ] = optDescription ;
}
this . ruleBodies [ name ] = body ;
return this ;
} ;
// Stuff that you should only do once
GrammarDecl . prototype . withSuperGrammar = function ( superGrammar ) {
if ( this . superGrammar ) {
throw new Error ( 'the super grammar of a GrammarDecl cannot be set more than once' ) ;
}
this . superGrammar = superGrammar ;
this . ruleBodies = Object . create ( superGrammar . ruleBodies ) ;
this . ruleFormals = Object . create ( superGrammar . ruleFormals ) ;
this . ruleDescriptions = Object . create ( superGrammar . ruleDescriptions ) ;
// Grammars with an explicit supergrammar inherit a default start rule.
if ( ! superGrammar . isBuiltIn ( ) ) {
this . defaultStartRule = superGrammar . defaultStartRule ;
}
return this ;
} ;
GrammarDecl . prototype . withDefaultStartRule = function ( ruleName ) {
this . defaultStartRule = ruleName ;
return this ;
} ;
GrammarDecl . prototype . withSource = function ( source ) {
2016-05-16 17:27:46 +00:00
this . interval = new InputStream ( source ) . interval ( 0 , source . length ) ;
2016-04-06 16:22:30 +00:00
return this ;
} ;
// Creates a Grammar instance, and if it passes the sanity checks, returns it.
GrammarDecl . prototype . build = function ( ) {
var grammar = new Grammar (
this . name ,
this . ensureSuperGrammar ( ) ,
this . ruleBodies ,
this . ruleFormals ,
this . ruleDescriptions ,
this . defaultStartRule ) ;
// TODO: change the pexpr.prototype.assert... methods to make them add
// exceptions to an array that's provided as an arg. Then we'll be able to
// show more than one error of the same type at a time.
// TODO: include the offending pexpr in the errors, that way we can show
// the part of the source that caused it.
var grammarErrors = [ ] ;
var grammarHasInvalidApplications = false ;
Object . keys ( grammar . ruleBodies ) . forEach ( function ( ruleName ) {
var body = grammar . ruleBodies [ ruleName ] ;
try {
body . assertChoicesHaveUniformArity ( ruleName ) ;
} catch ( e ) {
grammarErrors . push ( e ) ;
}
try {
body . assertAllApplicationsAreValid ( ruleName , grammar ) ;
} catch ( e ) {
grammarErrors . push ( e ) ;
grammarHasInvalidApplications = true ;
}
} ) ;
if ( ! grammarHasInvalidApplications ) {
// The following check can only be done if the grammar has no invalid applications.
Object . keys ( grammar . ruleBodies ) . forEach ( function ( ruleName ) {
var body = grammar . ruleBodies [ ruleName ] ;
try {
body . assertIteratedExprsAreNotNullable ( grammar , ruleName ) ;
} catch ( e ) {
grammarErrors . push ( e ) ;
}
} ) ;
}
if ( grammarErrors . length > 0 ) {
errors . throwErrors ( grammarErrors ) ;
}
if ( this . interval ) {
grammar . definitionInterval = this . interval ;
}
return grammar ;
} ;
// Rule declarations
GrammarDecl . prototype . define = function ( name , formals , body , optDescr ) {
this . ensureSuperGrammar ( ) ;
if ( this . superGrammar . ruleBodies [ name ] ) {
throw errors . duplicateRuleDeclaration ( name , this . name , this . superGrammar . name , body ) ;
} else if ( this . ruleBodies [ name ] ) {
throw errors . duplicateRuleDeclaration ( name , this . name , this . name , body ) ;
}
var duplicateParameterNames = common . getDuplicates ( formals ) ;
if ( duplicateParameterNames . length > 0 ) {
throw errors . duplicateParameterNames ( name , duplicateParameterNames , body ) ;
}
return this . install ( name , formals , body , optDescr ) ;
} ;
GrammarDecl . prototype . override = function ( name , formals , body ) {
var baseRule = this . ensureSuperGrammar ( ) . ruleBodies [ name ] ;
if ( ! baseRule ) {
throw errors . cannotOverrideUndeclaredRule ( name , this . superGrammar . name , body ) ;
}
this . installOverriddenOrExtendedRule ( name , formals , body ) ;
return this ;
} ;
GrammarDecl . prototype . extend = function ( name , formals , fragment ) {
var baseRule = this . ensureSuperGrammar ( ) . ruleBodies [ name ] ;
if ( ! baseRule ) {
throw errors . cannotExtendUndeclaredRule ( name , this . superGrammar . name , fragment ) ;
}
var body = new pexprs . Extend ( this . superGrammar , name , fragment ) ;
body . interval = fragment . interval ;
this . installOverriddenOrExtendedRule ( name , formals , body ) ;
return this ;
} ;
// --------------------------------------------------------------------
// Exports
// --------------------------------------------------------------------
module . exports = GrammarDecl ;
2016-05-16 17:27:46 +00:00
} , { "./Grammar" : 38 , "./InputStream" : 40 , "./common" : 48 , "./errors" : 49 , "./pexprs" : 67 } ] , 40 : [ function ( require , module , exports ) {
2016-04-06 16:22:30 +00:00
'use strict' ;
// --------------------------------------------------------------------
// Imports
// --------------------------------------------------------------------
var Interval = require ( './Interval' ) ;
// --------------------------------------------------------------------
// Private stuff
// --------------------------------------------------------------------
2016-05-16 17:27:46 +00:00
function InputStream ( source ) {
this . source = source ;
this . pos = 0 ;
this . posInfos = [ ] ;
2016-04-06 16:22:30 +00:00
}
InputStream . prototype = {
atEnd : function ( ) {
return this . pos === this . source . length ;
} ,
next : function ( ) {
2016-05-16 17:27:46 +00:00
return this . source [ this . pos ++ ] ;
2016-04-06 16:22:30 +00:00
} ,
2016-05-16 17:27:46 +00:00
matchString : function ( s ) {
for ( var idx = 0 ; idx < s . length ; idx ++ ) {
if ( this . next ( ) !== s [ idx ] ) {
return false ;
}
}
return true ;
2016-04-06 16:22:30 +00:00
} ,
sourceSlice : function ( startIdx , endIdx ) {
return this . source . slice ( startIdx , endIdx ) ;
} ,
interval : function ( startIdx , optEndIdx ) {
return new Interval ( this , startIdx , optEndIdx ? optEndIdx : this . pos ) ;
}
} ;
// --------------------------------------------------------------------
// Exports
// --------------------------------------------------------------------
module . exports = InputStream ;
2016-05-16 17:27:46 +00:00
} , { "./Interval" : 41 } ] , 41 : [ function ( require , module , exports ) {
2016-04-06 16:22:30 +00:00
'use strict' ;
// --------------------------------------------------------------------
// Imports
// --------------------------------------------------------------------
var assert = require ( './common' ) . assert ;
var errors = require ( './errors' ) ;
var util = require ( './util' ) ;
// --------------------------------------------------------------------
// Private stuff
// --------------------------------------------------------------------
function Interval ( inputStream , startIdx , endIdx ) {
this . inputStream = inputStream ;
this . startIdx = startIdx ;
this . endIdx = endIdx ;
}
Interval . coverage = function ( /* interval1, interval2, ... */ ) {
var inputStream = arguments [ 0 ] . inputStream ;
var startIdx = arguments [ 0 ] . startIdx ;
var endIdx = arguments [ 0 ] . endIdx ;
for ( var idx = 1 ; idx < arguments . length ; idx ++ ) {
var interval = arguments [ idx ] ;
if ( interval . inputStream !== inputStream ) {
throw errors . intervalSourcesDontMatch ( ) ;
} else {
startIdx = Math . min ( startIdx , arguments [ idx ] . startIdx ) ;
endIdx = Math . max ( endIdx , arguments [ idx ] . endIdx ) ;
}
}
return new Interval ( inputStream , startIdx , endIdx ) ;
} ;
Interval . prototype = {
coverageWith : function ( /* interval1, interval2, ... */ ) {
var intervals = Array . prototype . slice . call ( arguments ) ;
intervals . push ( this ) ;
return Interval . coverage . apply ( undefined , intervals ) ;
} ,
collapsedLeft : function ( ) {
return new Interval ( this . inputStream , this . startIdx , this . startIdx ) ;
} ,
collapsedRight : function ( ) {
return new Interval ( this . inputStream , this . endIdx , this . endIdx ) ;
} ,
getLineAndColumnMessage : function ( ) {
var range = [ this . startIdx , this . endIdx ] ;
return util . getLineAndColumnMessage ( this . inputStream . source , this . startIdx , range ) ;
} ,
// Returns an array of 0, 1, or 2 intervals that represents the result of the
// interval difference operation.
minus : function ( that ) {
if ( this . inputStream !== that . inputStream ) {
throw errors . intervalSourcesDontMatch ( ) ;
} else if ( this . startIdx === that . startIdx && this . endIdx === that . endIdx ) {
// `this` and `that` are the same interval!
return [
] ;
} else if ( this . startIdx < that . startIdx && that . endIdx < this . endIdx ) {
// `that` splits `this` into two intervals
return [
new Interval ( this . inputStream , this . startIdx , that . startIdx ) ,
new Interval ( this . inputStream , that . endIdx , this . endIdx )
] ;
} else if ( this . startIdx < that . endIdx && that . endIdx < this . endIdx ) {
// `that` contains a prefix of `this`
return [
new Interval ( this . inputStream , that . endIdx , this . endIdx )
] ;
} else if ( this . startIdx < that . startIdx && that . startIdx < this . endIdx ) {
// `that` contains a suffix of `this`
return [
new Interval ( this . inputStream , this . startIdx , that . startIdx )
] ;
} else {
// `that` and `this` do not overlap
return [
this
] ;
}
} ,
// Returns a new Interval that has the same extent as this one, but which is relative
// to `that`, an Interval that fully covers this one.
relativeTo : function ( that , newInputStream ) {
if ( this . inputStream !== that . inputStream ) {
throw errors . intervalSourcesDontMatch ( ) ;
}
assert ( this . startIdx >= that . startIdx && this . endIdx <= that . endIdx ,
'other interval does not cover this one' ) ;
return new Interval ( newInputStream ,
this . startIdx - that . startIdx ,
this . endIdx - that . startIdx ) ;
} ,
// Returns a new Interval which contains the same contents as this one,
// but with whitespace trimmed from both ends. (This only makes sense when
// the input stream is a string.)
trimmed : function ( ) {
var contents = this . contents ;
var startIdx = this . startIdx + contents . match ( /^\s*/ ) [ 0 ] . length ;
var endIdx = this . endIdx - contents . match ( /\s*$/ ) [ 0 ] . length ;
return new Interval ( this . inputStream , startIdx , endIdx ) ;
}
} ;
Object . defineProperties ( Interval . prototype , {
contents : {
get : function ( ) {
if ( this . _contents === undefined ) {
this . _contents = this . inputStream . sourceSlice ( this . startIdx , this . endIdx ) ;
}
return this . _contents ;
} ,
enumerable : true
}
} ) ;
// --------------------------------------------------------------------
// Exports
// --------------------------------------------------------------------
module . exports = Interval ;
2016-05-16 17:27:46 +00:00
} , { "./common" : 48 , "./errors" : 49 , "./util" : 68 } ] , 42 : [ function ( require , module , exports ) {
2016-04-06 16:22:30 +00:00
'use strict' ;
// --------------------------------------------------------------------
// Imports
// --------------------------------------------------------------------
var inherits = require ( 'inherits' ) ;
var common = require ( './common' ) ;
var nodes = require ( './nodes' ) ;
var util = require ( './util' ) ;
var Interval = require ( './Interval' ) ;
// --------------------------------------------------------------------
// Private stuff
// --------------------------------------------------------------------
// Create a short error message for an error that occurred during matching.
function getShortMatchErrorMessage ( pos , source , detail ) {
var errorInfo = util . getLineAndColumn ( source , pos ) ;
return 'Line ' + errorInfo . lineNum + ', col ' + errorInfo . colNum + ': ' + detail ;
}
// ----------------- MatchFailure -----------------
function MatchResult ( state ) {
this . state = state ;
this . _cst = state . bindings [ 0 ] ;
}
MatchResult . newFor = function ( state ) {
2016-05-02 21:15:05 +00:00
var succeeded = state . bindings . length > 0 ;
2016-04-06 16:22:30 +00:00
return succeeded ? new MatchResult ( state ) : new MatchFailure ( state ) ;
} ;
MatchResult . prototype . failed = function ( ) {
return false ;
} ;
MatchResult . prototype . succeeded = function ( ) {
return ! this . failed ( ) ;
} ;
// Returns a `MatchResult` that can be fed into operations or attributes that care
// about the whitespace that was implicitly skipped over by syntactic rules. This
// is useful for doing things with comments, e.g., syntax highlighting.
MatchResult . prototype . getDiscardedSpaces = function ( ) {
if ( this . failed ( ) ) {
return [ ] ;
}
var state = this . state ;
var grammar = state . grammar ;
var inputStream = state . inputStream ;
var intervals = [ new Interval ( inputStream , 0 , inputStream . source . length ) ] ;
// Subtract the interval of each terminal from the set of intervals above.
var s = grammar . semantics ( ) . addOperation ( 'subtractTerminals' , {
_nonterminal : function ( children ) {
children . forEach ( function ( child ) {
child . subtractTerminals ( ) ;
} ) ;
} ,
_terminal : function ( ) {
var t = this ;
intervals = intervals .
map ( function ( interval ) { return interval . minus ( t . interval ) ; } ) .
reduce ( function ( xs , ys ) { return xs . concat ( ys ) ; } , [ ] ) ;
}
} ) ;
s ( this ) . subtractTerminals ( ) ;
// Now `intervals` holds the intervals of the input stream that were skipped over by syntactic
// rules, because they contained spaces.
// Next, we want to match the contents of each of those intervals with the grammar's `spaces`
// rule, to reconstruct the CST nodes that were discarded by syntactic rules. But if we simply
// pass each interval's `contents` to the grammar's `match` method, the resulting nodes and
// their children will have intervals that are associated with a different input, i.e., a
// substring of the original input. The following operation will fix this problem for us.
s . addOperation ( 'fixIntervals(idxOffset)' , {
_default : function ( children ) {
var idxOffset = this . args . idxOffset ;
this . interval . inputStream = inputStream ;
this . interval . startIdx += idxOffset ;
this . interval . endIdx += idxOffset ;
if ( ! this . isTerminal ( ) ) {
children . forEach ( function ( child ) {
child . fixIntervals ( idxOffset ) ;
} ) ;
}
}
} ) ;
// Now we're finally ready to reconstruct the discarded CST nodes.
var discardedNodes = intervals . map ( function ( interval ) {
var r = grammar . match ( interval . contents , 'spaces' ) ;
s ( r ) . fixIntervals ( interval . startIdx ) ;
return r . _cst ;
} ) ;
// Rather than return a bunch of CST nodes and make the caller of this method loop over them,
// we can construct a single CST node that is the parent of all of the discarded nodes. An
// `IterationNode` is the obvious choice for this.
discardedNodes = new nodes . IterationNode (
grammar ,
discardedNodes ,
discardedNodes . length === 0 ?
new Interval ( inputStream , 0 , 0 ) :
new Interval (
inputStream ,
discardedNodes [ 0 ] . interval . startIdx ,
discardedNodes [ discardedNodes . length - 1 ] . interval . endIdx ) ) ;
// But remember that a CST node can't be used directly by clients. What we really need to return
// from this method is a successful `MatchResult` that can be used with the clients' semantics.
// We already have one -- `this` -- but it's got a different CST node inside. So we create a new
// object that delegates to `this`, and override its `_cst` property.
var r = Object . create ( this ) ;
r . _cst = discardedNodes ;
// We also override its `getDiscardedSpaces` method, in case someone decides to call it.
r . getDiscardedSpaces = function ( ) { return r ; } ;
return r ;
} ;
// ----------------- MatchFailure -----------------
function MatchFailure ( state ) {
this . state = state ;
common . defineLazyProperty ( this , '_failures' , function ( ) {
return this . state . getFailures ( ) ;
} ) ;
common . defineLazyProperty ( this , 'message' , function ( ) {
var source = this . state . inputStream . source ;
if ( typeof source !== 'string' ) {
return 'match failed at position ' + this . getRightmostFailurePosition ( ) ;
}
var detail = 'Expected ' + this . getExpectedText ( ) ;
return util . getLineAndColumnMessage ( source , this . getRightmostFailurePosition ( ) ) + detail ;
} ) ;
common . defineLazyProperty ( this , 'shortMessage' , function ( ) {
if ( typeof this . state . inputStream . source !== 'string' ) {
return 'match failed at position ' + this . getRightmostFailurePosition ( ) ;
}
var detail = 'expected ' + this . getExpectedText ( ) ;
return getShortMatchErrorMessage (
this . getRightmostFailurePosition ( ) ,
this . state . inputStream . source ,
detail ) ;
} ) ;
}
inherits ( MatchFailure , MatchResult ) ;
MatchFailure . prototype . toString = function ( ) {
return '[MatchFailure at position ' + this . getRightmostFailurePosition ( ) + ']' ;
} ;
MatchFailure . prototype . failed = function ( ) {
return true ;
} ;
MatchFailure . prototype . getRightmostFailurePosition = function ( ) {
return this . state . getRightmostFailurePosition ( ) ;
} ;
MatchFailure . prototype . getRightmostFailures = function ( ) {
return this . _failures ;
} ;
// Return a string summarizing the expected contents of the input stream when
// the match failure occurred.
MatchFailure . prototype . getExpectedText = function ( ) {
var sb = new common . StringBuffer ( ) ;
var failures = this . getRightmostFailures ( ) ;
// Filter out the fluffy failures to make the default error messages more useful
failures = failures . filter ( function ( failure ) {
return ! failure . isFluffy ( ) ;
} ) ;
for ( var idx = 0 ; idx < failures . length ; idx ++ ) {
if ( idx > 0 ) {
if ( idx === failures . length - 1 ) {
sb . append ( ( failures . length > 2 ? ', or ' : ' or ' ) ) ;
} else {
sb . append ( ', ' ) ;
}
}
sb . append ( failures [ idx ] . toString ( ) ) ;
}
return sb . contents ( ) ;
} ;
MatchFailure . prototype . getInterval = function ( ) {
var pos = this . state . getRightmostFailurePosition ( ) ;
return new Interval ( this . state . inputStream , pos , pos ) ;
} ;
// --------------------------------------------------------------------
// Exports
// --------------------------------------------------------------------
module . exports = MatchResult ;
2016-05-16 17:27:46 +00:00
} , { "./Interval" : 41 , "./common" : 48 , "./nodes" : 51 , "./util" : 68 , "inherits" : 33 } ] , 43 : [ function ( require , module , exports ) {
2016-04-06 16:22:30 +00:00
'use strict' ;
// --------------------------------------------------------------------
// Imports
// --------------------------------------------------------------------
var extend = require ( 'util-extend' ) ;
// --------------------------------------------------------------------
// Private stuff
// --------------------------------------------------------------------
function Namespace ( ) {
}
Namespace . prototype = Object . create ( null ) ;
Namespace . asNamespace = function ( objOrNamespace ) {
if ( objOrNamespace instanceof Namespace ) {
return objOrNamespace ;
}
return Namespace . createNamespace ( objOrNamespace ) ;
} ;
// Create a new namespace. If `optProps` is specified, all of its properties
// will be copied to the new namespace.
Namespace . createNamespace = function ( optProps ) {
return Namespace . extend ( Namespace . prototype , optProps ) ;
} ;
// Create a new namespace which extends another namespace. If `optProps` is
// specified, all of its properties will be copied to the new namespace.
Namespace . extend = function ( namespace , optProps ) {
if ( namespace !== Namespace . prototype && ! ( namespace instanceof Namespace ) ) {
throw new TypeError ( 'not a Namespace object: ' + namespace ) ;
}
var ns = Object . create ( namespace , {
constructor : {
value : Namespace ,
enumerable : false ,
writable : true ,
configurable : true
}
} ) ;
return extend ( ns , optProps ) ;
} ;
// TODO: Should this be a regular method?
Namespace . toString = function ( ns ) {
return Object . prototype . toString . call ( ns ) ;
} ;
// --------------------------------------------------------------------
// Exports
// --------------------------------------------------------------------
module . exports = Namespace ;
} , { "util-extend" : 35 } ] , 44 : [ function ( require , module , exports ) {
'use strict' ;
// --------------------------------------------------------------------
// Private stuff
// --------------------------------------------------------------------
function PosInfo ( state ) {
this . state = state ;
this . applicationMemoKeyStack = [ ] ; // a stack of "memo keys" of the active applications
this . memo = { } ;
this . currentLeftRecursion = undefined ;
}
PosInfo . prototype = {
isActive : function ( application ) {
return this . applicationMemoKeyStack . indexOf ( application . toMemoKey ( ) ) >= 0 ;
} ,
enter : function ( application ) {
this . state . enter ( application ) ;
this . applicationMemoKeyStack . push ( application . toMemoKey ( ) ) ;
} ,
exit : function ( ) {
this . state . exit ( ) ;
this . applicationMemoKeyStack . pop ( ) ;
} ,
startLeftRecursion : function ( headApplication , memoRec ) {
memoRec . isLeftRecursion = true ;
memoRec . headApplication = headApplication ;
memoRec . nextLeftRecursion = this . currentLeftRecursion ;
this . currentLeftRecursion = memoRec ;
var applicationMemoKeyStack = this . applicationMemoKeyStack ;
var indexOfFirstInvolvedRule = applicationMemoKeyStack . indexOf ( headApplication . toMemoKey ( ) ) + 1 ;
var involvedApplicationMemoKeys = applicationMemoKeyStack . slice ( indexOfFirstInvolvedRule ) ;
memoRec . isInvolved = function ( applicationMemoKey ) {
return involvedApplicationMemoKeys . indexOf ( applicationMemoKey ) >= 0 ;
} ;
memoRec . updateInvolvedApplicationMemoKeys = function ( ) {
for ( var idx = indexOfFirstInvolvedRule ; idx < applicationMemoKeyStack . length ; idx ++ ) {
var applicationMemoKey = applicationMemoKeyStack [ idx ] ;
if ( ! this . isInvolved ( applicationMemoKey ) ) {
involvedApplicationMemoKeys . push ( applicationMemoKey ) ;
}
}
} ;
} ,
endLeftRecursion : function ( ) {
this . currentLeftRecursion = this . currentLeftRecursion . nextLeftRecursion ;
} ,
// Note: this method doesn't get called for the "head" of a left recursion -- for LR heads,
// the memoized result (which starts out being a failure) is always used.
shouldUseMemoizedResult : function ( memoRec ) {
if ( ! memoRec . isLeftRecursion ) {
return true ;
}
var applicationMemoKeyStack = this . applicationMemoKeyStack ;
for ( var idx = 0 ; idx < applicationMemoKeyStack . length ; idx ++ ) {
var applicationMemoKey = applicationMemoKeyStack [ idx ] ;
if ( memoRec . isInvolved ( applicationMemoKey ) ) {
return false ;
}
}
return true ;
}
} ;
// --------------------------------------------------------------------
// Exports
// --------------------------------------------------------------------
module . exports = PosInfo ;
} , { } ] , 45 : [ function ( require , module , exports ) {
'use strict' ;
// --------------------------------------------------------------------
// Imports
// --------------------------------------------------------------------
var Symbol = require ( 'es6-symbol' ) ; // eslint-disable-line no-undef
var inherits = require ( 'inherits' ) ;
var MatchResult = require ( './MatchResult' ) ;
var IterationNode = require ( './nodes' ) . IterationNode ;
var common = require ( './common' ) ;
// --------------------------------------------------------------------
// Private stuff
// --------------------------------------------------------------------
// ----------------- Wrappers -----------------
// Wrappers decorate CST nodes with all of the functionality (i.e., operations and attributes)
// provided by a Semantics (see below). `Wrapper` is the abstract superclass of all wrappers. A
// `Wrapper` must have `_node` and `_semantics` instance variables, which refer to the CST node and
// Semantics (resp.) for which it was created, and a `_childWrappers` instance variable which is
// used to cache the wrapper instances that are created for its child nodes. Setting these instance
// variables is the responsibility of the constructor of each Semantics-specific subclass of
// `Wrapper`.
function Wrapper ( ) { }
Wrapper . prototype . toString = function ( ) {
return '[semantics wrapper for ' + this . _node . grammar . name + ']' ;
} ;
2016-05-02 21:15:05 +00:00
Wrapper . prototype . _forgetMemoizedResultFor = function ( attributeName ) {
// Remove the memoized attribute from the cstNode and all its children.
delete this . _node [ this . _semantics . attributeKeys [ attributeName ] ] ;
this . children . forEach ( function ( child ) {
child . _forgetMemoizedResultFor ( attributeName ) ;
} ) ;
} ;
2016-04-06 16:22:30 +00:00
// Returns the wrapper of the specified child node. Child wrappers are created lazily and cached in
// the parent wrapper's `_childWrappers` instance variable.
Wrapper . prototype . child = function ( idx ) {
if ( ! ( 0 <= idx && idx < this . _node . numChildren ( ) ) ) {
// TODO: Consider throwing an exception here.
return undefined ;
}
var childWrapper = this . _childWrappers [ idx ] ;
if ( ! childWrapper ) {
childWrapper = this . _childWrappers [ idx ] = this . _semantics . wrap ( this . _node . childAt ( idx ) ) ;
}
return childWrapper ;
} ;
// Returns an array containing the wrappers of all of the children of the node associated with this
// wrapper.
Wrapper . prototype . _children = function ( ) {
// Force the creation of all child wrappers
for ( var idx = 0 ; idx < this . _node . numChildren ( ) ; idx ++ ) {
this . child ( idx ) ;
}
return this . _childWrappers ;
} ;
// Returns `true` if the CST node associated with this wrapper corresponds to an iteration
// expression, i.e., a Kleene-*, Kleene-+, or an optional. Returns `false` otherwise.
Wrapper . prototype . isIteration = function ( ) {
return this . _node . isIteration ( ) ;
} ;
// Returns `true` if the CST node associated with this wrapper is a terminal node, `false`
// otherwise.
Wrapper . prototype . isTerminal = function ( ) {
return this . _node . isTerminal ( ) ;
} ;
// Returns `true` if the CST node associated with this wrapper is a nonterminal node, `false`
// otherwise.
Wrapper . prototype . isNonterminal = function ( ) {
return this . _node . isNonterminal ( ) ;
} ;
// Returns `true` if the CST node associated with this wrapper is a nonterminal node
// corresponding to a syntactic rule, `false` otherwise.
Wrapper . prototype . isSyntactic = function ( ) {
return this . isNonterminal ( ) && this . _node . isSyntactic ( ) ;
} ;
// Returns `true` if the CST node associated with this wrapper is a nonterminal node
// corresponding to a lexical rule, `false` otherwise.
Wrapper . prototype . isLexical = function ( ) {
return this . isNonterminal ( ) && this . _node . isLexical ( ) ;
} ;
// Returns `true` if the CST node associated with this wrapper is an iterator node
// having either one or no child (? operator), `false` otherwise.
// Otherwise, throws an exception.
Wrapper . prototype . isOptional = function ( ) {
return this . _node . isOptional ( ) ;
} ;
// Create a new IterationNode in the same semantics as this wrapper.
Wrapper . prototype . iteration = function ( optElements ) {
var iter = new IterationNode ( this . _node . grammar , optElements || [ ] , this . interval , false ) ;
return this . _semantics . wrap ( iter ) ;
} ;
Object . defineProperties ( Wrapper . prototype , {
// Returns an array containing the children of this CST node.
children : { get : function ( ) { return this . _children ( ) ; } } ,
// Returns the name of grammar rule that created this CST node.
ctorName : { get : function ( ) { return this . _node . ctorName ; } } ,
// Returns the interval consumed by the CST node associated with this wrapper.
interval : { get : function ( ) { return this . _node . interval ; } } ,
// Returns the number of children of this CST node.
numChildren : { get : function ( ) { return this . _node . numChildren ( ) ; } } ,
// Returns the primitive value of this CST node, if it's a terminal node. Otherwise,
// throws an exception.
primitiveValue : {
get : function ( ) {
if ( this . isTerminal ( ) ) {
return this . _node . primitiveValue ;
}
throw new TypeError (
"tried to access the 'primitiveValue' attribute of a non-terminal CST node" ) ;
}
}
} ) ;
// ----------------- Semantics -----------------
// A Semantics is a container for a family of Operations and Attributes for a given grammar.
// Semantics enable modularity (different clients of a grammar can create their set of operations
// and attributes in isolation) and extensibility even when operations and attributes are mutually-
// recursive. This constructor should not be called directly except from
// `Semantics.createSemantics`. The normal ways to create a Semantics, given a grammar 'g', are
// `g.semantics()` and `g.extendSemantics(parentSemantics)`.
function Semantics ( grammar , superSemantics ) {
var self = this ;
this . grammar = grammar ;
this . checkedActionDicts = false ;
// Constructor for wrapper instances, which are passed as the arguments to the semantic actions
// of an operation or attribute. Operations and attributes require double dispatch: the semantic
// action is chosen based on both the node's type and the semantics. Wrappers ensure that
// the `execute` method is called with the correct (most specific) semantics object as an
// argument.
this . Wrapper = function ( node ) {
self . checkActionDictsIfHaventAlready ( ) ;
this . _semantics = self ;
this . _node = node ;
this . _childWrappers = [ ] ;
} ;
this . super = superSemantics ;
if ( superSemantics ) {
if ( grammar !== this . super . grammar && ! grammar . _inheritsFrom ( this . super . grammar ) ) {
throw new Error (
"Cannot extend a semantics for grammar '" + this . super . grammar . name +
"' for use with grammar '" + grammar . name + "' (not a sub-grammar)" ) ;
}
inherits ( this . Wrapper , this . super . Wrapper ) ;
this . operations = Object . create ( this . super . operations ) ;
this . attributes = Object . create ( this . super . attributes ) ;
this . attributeKeys = Object . create ( null ) ;
// Assign unique symbols for each of the attributes inherited from the super-semantics so that
// they are memoized independently.
for ( var attributeName in this . attributes ) {
this . attributeKeys [ attributeName ] = Symbol ( ) ;
}
} else {
inherits ( this . Wrapper , Wrapper ) ;
this . operations = Object . create ( null ) ;
this . attributes = Object . create ( null ) ;
this . attributeKeys = Object . create ( null ) ;
}
}
Semantics . prototype . toString = function ( ) {
return '[semantics for ' + this . grammar . name + ']' ;
} ;
Semantics . prototype . checkActionDictsIfHaventAlready = function ( ) {
if ( ! this . checkedActionDicts ) {
this . checkActionDicts ( ) ;
this . checkedActionDicts = true ;
}
} ;
// Checks that the action dictionaries for all operations and attributes in this semantics,
// including the ones that were inherited from the super-semantics, agree with the grammar.
// Throws an exception if one or more of them doesn't.
Semantics . prototype . checkActionDicts = function ( ) {
for ( var name in this . operations ) {
this . operations [ name ] . checkActionDict ( this . grammar ) ;
}
for ( name in this . attributes ) {
this . attributes [ name ] . checkActionDict ( this . grammar ) ;
}
} ;
2016-05-16 17:27:46 +00:00
Semantics . prototype . toRecipe = function ( semanticsOnly ) {
function hasSuperSemantics ( s ) {
return s . super !== Semantics . BuiltInSemantics . _getSemantics ( ) ;
}
var str = '(function(g) {\n' ;
if ( hasSuperSemantics ( this ) ) {
str += ' var semantics = ' + this . super . toRecipe ( true ) + '(g' ;
var superSemanticsGrammar = this . super . grammar ;
var relatedGrammar = this . grammar ;
while ( relatedGrammar !== superSemanticsGrammar ) {
str += '.superGrammar' ;
relatedGrammar = relatedGrammar . superGrammar ;
}
str += ');\n' ;
str += ' return g.extendSemantics(semantics)' ;
} else {
str += ' return g.semantics()' ;
}
[ 'Operation' , 'Attribute' ] . forEach ( function ( type ) {
var semanticOperations = this [ type . toLowerCase ( ) + 's' ] ;
Object . keys ( semanticOperations ) . forEach ( function ( name ) {
var signature = name ;
if ( semanticOperations [ name ] . formals . length > 0 ) {
signature += '(' + semanticOperations [ name ] . formals . join ( ', ' ) + ')' ;
}
var method ;
if ( hasSuperSemantics ( this ) && this . super [ type . toLowerCase ( ) + 's' ] [ name ] ) {
method = 'extend' + type ;
} else {
method = 'add' + type ;
}
str += '\n .' + method + '(' + JSON . stringify ( signature ) + ', {' ;
var actions = semanticOperations [ name ] . actionDict ;
var srcArray = [ ] ;
Object . keys ( actions ) . forEach ( function ( actionName ) {
if ( semanticOperations [ name ] . builtInDefault !== actions [ actionName ] ) {
srcArray . push ( '\n ' + JSON . stringify ( actionName ) + ': ' +
actions [ actionName ] . toString ( ) ) ;
}
} ) ;
str += srcArray . join ( ',' ) ;
str += '\n })' ;
} , this ) ;
} , this ) ;
str += ';\n })' ;
if ( ! semanticsOnly ) {
str =
'(function() {\n' +
2016-08-07 19:41:10 +00:00
' var buildGrammar = ' + this . grammar . toRecipe ( ) +
' var grammar = buildGrammar.call(this);\n' +
2016-05-16 17:27:46 +00:00
' var semantics = ' + str + '(grammar);\n' +
' return semantics;\n' +
'});\n' ;
}
return str ;
} ;
2016-04-06 16:22:30 +00:00
var prototypeGrammar ;
var prototypeGrammarSemantics ;
// This method is called from main.js once Ohm has loaded.
Semantics . initPrototypeParser = function ( grammar ) {
prototypeGrammarSemantics = grammar . semantics ( ) . addOperation ( 'parse' , {
2016-05-02 21:15:05 +00:00
AttributeSignature : function ( name ) {
2016-04-06 16:22:30 +00:00
return {
2016-05-02 21:15:05 +00:00
name : name . parse ( ) ,
2016-04-06 16:22:30 +00:00
formals : [ ]
} ;
} ,
2016-05-02 21:15:05 +00:00
OperationSignature : function ( name , optFormals ) {
2016-04-06 16:22:30 +00:00
return {
2016-05-02 21:15:05 +00:00
name : name . parse ( ) ,
formals : optFormals . parse ( ) [ 0 ] || [ ]
2016-04-06 16:22:30 +00:00
} ;
} ,
Formals : function ( oparen , fs , cparen ) {
return fs . asIteration ( ) . parse ( ) ;
} ,
name : function ( first , rest ) {
return this . interval . contents ;
}
} ) ;
prototypeGrammar = grammar ;
} ;
2016-05-02 21:15:05 +00:00
function parseSignature ( signature , type ) {
2016-04-06 16:22:30 +00:00
if ( ! prototypeGrammar ) {
// The Operations and Attributes grammar won't be available while Ohm is loading,
// but we can get away the following simplification b/c none of the operations
// that are used while loading take arguments.
2016-05-02 21:15:05 +00:00
common . assert ( signature . indexOf ( '(' ) === - 1 ) ;
2016-04-06 16:22:30 +00:00
return {
2016-05-02 21:15:05 +00:00
name : signature ,
2016-04-06 16:22:30 +00:00
formals : [ ]
} ;
}
var r = prototypeGrammar . match (
2016-05-02 21:15:05 +00:00
signature ,
type === 'operation' ? 'OperationSignature' : 'AttributeSignature' ) ;
2016-04-06 16:22:30 +00:00
if ( r . failed ( ) ) {
throw new Error ( r . message ) ;
}
return prototypeGrammarSemantics ( r ) . parse ( ) ;
}
2016-05-16 17:27:46 +00:00
function newDefaultAction ( type , name , doIt ) {
return function ( children ) {
var self = this ;
var thisThing = this . _semantics . operations [ name ] || this . _semantics . attributes [ name ] ;
var args = thisThing . formals . map ( function ( formal ) {
return self . args [ formal ] ;
} ) ;
if ( this . isIteration ( ) ) {
// This CST node corresponds to an iteration expression in the grammar (*, +, or ?). The
// default behavior is to map this operation or attribute over all of its child nodes.
return children . map ( function ( child ) { return doIt . apply ( child , args ) ; } ) ;
}
// This CST node corresponds to a non-terminal in the grammar (e.g., AddExpr). The fact that
// we got here means that this action dictionary doesn't have an action for this particular
// non-terminal or a generic `_nonterminal` action.
if ( children . length === 1 ) {
// As a convenience, if this node only has one child, we just return the result of
// applying this operation / attribute to the child node.
return doIt . apply ( children [ 0 ] , args ) ;
} else {
// Otherwise, we throw an exception to let the programmer know that we don't know what
// to do with this node.
throw new Error (
'Missing semantic action for ' + this . ctorName + ' in ' + name + ' ' + type ) ;
}
} ;
}
2016-05-02 21:15:05 +00:00
Semantics . prototype . addOperationOrAttribute = function ( type , signature , actionDict ) {
2016-04-06 16:22:30 +00:00
var typePlural = type + 's' ;
2016-05-02 21:15:05 +00:00
var parsedNameAndFormalArgs = parseSignature ( signature , type ) ;
2016-04-06 16:22:30 +00:00
var name = parsedNameAndFormalArgs . name ;
var formals = parsedNameAndFormalArgs . formals ;
// TODO: check that there are no duplicate formal arguments
this . assertNewName ( name , type ) ;
// Create the action dictionary for this operation / attribute that contains a `_default` action
// which defines the default behavior of iteration, terminal, and non-terminal nodes...
2016-05-16 17:27:46 +00:00
var builtInDefault = newDefaultAction ( type , name , doIt ) ;
var realActionDict = { _default : builtInDefault } ;
2016-04-06 16:22:30 +00:00
// ... and add in the actions supplied by the programmer, which may override some or all of the
// default ones.
Object . keys ( actionDict ) . forEach ( function ( name ) {
realActionDict [ name ] = actionDict [ name ] ;
} ) ;
var entry = type === 'operation' ?
2016-05-16 17:27:46 +00:00
new Operation ( name , formals , realActionDict , builtInDefault ) :
new Attribute ( name , realActionDict , builtInDefault ) ;
2016-04-06 16:22:30 +00:00
// The following check is not strictly necessary (it will happen later anyway) but it's better to
// catch errors early.
entry . checkActionDict ( this . grammar ) ;
this [ typePlural ] [ name ] = entry ;
function doIt ( ) {
// Dispatch to most specific version of this operation / attribute -- it may have been
// overridden by a sub-semantics.
var thisThing = this . _semantics [ typePlural ] [ name ] ;
// Check that the caller passed the correct number of arguments.
if ( arguments . length !== thisThing . formals . length ) {
throw new Error (
'Invalid number of arguments passed to ' + name + ' ' + type + ' (expected ' +
thisThing . formals . length + ', got ' + arguments . length + ')' ) ;
}
// Create an "arguments object" from the arguments that were passed to this
// operation / attribute.
var args = Object . create ( null ) ;
for ( var idx = 0 ; idx < arguments . length ; idx ++ ) {
var formal = thisThing . formals [ idx ] ;
args [ formal ] = arguments [ idx ] ;
}
var oldArgs = this . args ;
this . args = args ;
var ans = thisThing . execute ( this . _semantics , this ) ;
this . args = oldArgs ;
return ans ;
}
if ( type === 'operation' ) {
this . Wrapper . prototype [ name ] = doIt ;
this . Wrapper . prototype [ name ] . toString = function ( ) {
return '[' + name + ' operation]' ;
} ;
} else {
2016-08-07 19:41:10 +00:00
Object . defineProperty ( this . Wrapper . prototype , name , { get : doIt } ) ;
2016-04-06 16:22:30 +00:00
this . attributeKeys [ name ] = Symbol ( ) ;
}
} ;
Semantics . prototype . extendOperationOrAttribute = function ( type , name , actionDict ) {
var typePlural = type + 's' ;
// Make sure that `name` really is just a name, i.e., that it doesn't also contain formals.
2016-05-02 21:15:05 +00:00
parseSignature ( name , 'attribute' ) ;
2016-04-06 16:22:30 +00:00
if ( ! ( this . super && name in this . super [ typePlural ] ) ) {
throw new Error ( 'Cannot extend ' + type + " '" + name +
"': did not inherit an " + type + ' with that name' ) ;
}
if ( Object . prototype . hasOwnProperty . call ( this [ typePlural ] , name ) ) {
throw new Error ( 'Cannot extend ' + type + " '" + name + "' again" ) ;
}
// Create a new operation / attribute whose actionDict delegates to the super operation /
// attribute's actionDict, and which has all the keys from `inheritedActionDict`.
var inheritedFormals = this [ typePlural ] [ name ] . formals ;
var inheritedActionDict = this [ typePlural ] [ name ] . actionDict ;
var newActionDict = Object . create ( inheritedActionDict ) ;
Object . keys ( actionDict ) . forEach ( function ( name ) {
newActionDict [ name ] = actionDict [ name ] ;
} ) ;
this [ typePlural ] [ name ] = type === 'operation' ?
new Operation ( name , inheritedFormals , newActionDict ) :
new Attribute ( name , newActionDict ) ;
// The following check is not strictly necessary (it will happen later anyway) but it's better to
// catch errors early.
this [ typePlural ] [ name ] . checkActionDict ( this . grammar ) ;
} ;
Semantics . prototype . assertNewName = function ( name , type ) {
if ( Wrapper . prototype . hasOwnProperty ( name ) ) {
throw new Error (
'Cannot add ' + type + " '" + name + "': that's a reserved name" ) ;
}
if ( name in this . operations ) {
throw new Error (
'Cannot add ' + type + " '" + name + "': an operation with that name already exists" ) ;
}
if ( name in this . attributes ) {
throw new Error (
'Cannot add ' + type + " '" + name + "': an attribute with that name already exists" ) ;
}
} ;
// Returns a wrapper for the given CST `node` in this semantics.
// If `node` is already a wrapper, returns `node` itself. // TODO: why is this needed?
Semantics . prototype . wrap = function ( node ) {
return node instanceof this . Wrapper ? node : new this . Wrapper ( node ) ;
} ;
// Creates a new Semantics instance for `grammar`, inheriting operations and attributes from
// `optSuperSemantics`, if it is specified. Returns a function that acts as a proxy for the new
// Semantics instance. When that function is invoked with a CST node as an argument, it returns
// a wrapper for that node which gives access to the operations and attributes provided by this
// semantics.
Semantics . createSemantics = function ( grammar , optSuperSemantics ) {
var s = new Semantics (
grammar ,
optSuperSemantics !== undefined ?
optSuperSemantics :
Semantics . BuiltInSemantics . _getSemantics ( ) ) ;
// To enable clients to invoke a semantics like a function, return a function that acts as a proxy
// for `s`, which is the real `Semantics` instance.
var proxy = function ASemantics ( matchResult ) {
if ( ! ( matchResult instanceof MatchResult ) ) {
throw new TypeError (
'Semantics expected a MatchResult, but got ' + common . unexpectedObjToString ( matchResult ) ) ;
}
if ( ! matchResult . succeeded ( ) ) {
throw new TypeError (
'cannot apply Semantics to ' + matchResult . toString ( ) ) ;
}
var cst = matchResult . _cst ;
if ( cst . grammar !== grammar ) {
throw new Error (
2016-08-07 19:41:10 +00:00
"Cannot use a CST node created by grammar '" + cst . grammar . name +
2016-04-06 16:22:30 +00:00
"' with a semantics for '" + grammar . name + "'" ) ;
}
return s . wrap ( cst ) ;
} ;
// Forward public methods from the proxy to the semantics instance.
2016-05-02 21:15:05 +00:00
proxy . addOperation = function ( signature , actionDict ) {
s . addOperationOrAttribute . call ( s , 'operation' , signature , actionDict ) ;
2016-04-06 16:22:30 +00:00
return proxy ;
} ;
proxy . extendOperation = function ( name , actionDict ) {
s . extendOperationOrAttribute . call ( s , 'operation' , name , actionDict ) ;
return proxy ;
} ;
proxy . addAttribute = function ( name , actionDict ) {
s . addOperationOrAttribute . call ( s , 'attribute' , name , actionDict ) ;
return proxy ;
} ;
proxy . extendAttribute = function ( name , actionDict ) {
s . extendOperationOrAttribute . call ( s , 'attribute' , name , actionDict ) ;
return proxy ;
} ;
2016-05-02 21:15:05 +00:00
proxy . _getActionDict = function ( operationOrAttributeName ) {
var action = s . operations [ operationOrAttributeName ] || s . attributes [ operationOrAttributeName ] ;
if ( ! action ) {
throw new Error ( '"' + operationOrAttributeName + '" is not a valid operation or attribute ' +
'name in this semantics for "' + grammar . name + '"' ) ;
}
return action . actionDict ;
} ;
2016-05-16 17:27:46 +00:00
proxy . getOperationNames = function ( ) {
return Object . keys ( s . operations ) ;
} ;
proxy . getAttributeNames = function ( ) {
return Object . keys ( s . attributes ) ;
} ;
proxy . getGrammar = function ( ) {
return s . grammar ;
} ;
proxy . toRecipe = function ( semanticsOnly ) {
return s . toRecipe ( semanticsOnly ) ;
} ;
2016-04-06 16:22:30 +00:00
// Make the proxy's toString() work.
proxy . toString = s . toString . bind ( s ) ;
// Returns the semantics for the proxy.
proxy . _getSemantics = function ( ) {
return s ;
} ;
return proxy ;
} ;
Semantics . initBuiltInSemantics = function ( builtInRules ) {
var actions = {
empty : function ( ) {
return this . iteration ( ) ;
} ,
nonEmpty : function ( first , _ , rest ) {
return this . iteration ( [ first ] . concat ( rest . children ) ) ;
}
} ;
Semantics . BuiltInSemantics = Semantics
. createSemantics ( builtInRules , null )
. addOperation ( 'asIteration' , {
emptyListOf : actions . empty ,
nonemptyListOf : actions . nonEmpty ,
EmptyListOf : actions . empty ,
NonemptyListOf : actions . nonEmpty
} ) ;
} ;
// ----------------- Operation -----------------
// An Operation represents a function to be applied to a concrete syntax tree (CST) -- it's very
// similar to a Visitor (http://en.wikipedia.org/wiki/Visitor_pattern). An operation is executed by
// recursively walking the CST, and at each node, invoking the matching semantic action from
// `actionDict`. See `Operation.prototype.execute` for details of how a CST node's matching semantic
// action is found.
2016-05-16 17:27:46 +00:00
function Operation ( name , formals , actionDict , builtInDefault ) {
2016-04-06 16:22:30 +00:00
this . name = name ;
this . formals = formals ;
this . actionDict = actionDict ;
2016-05-16 17:27:46 +00:00
this . builtInDefault = builtInDefault ;
2016-04-06 16:22:30 +00:00
}
Operation . prototype . typeName = 'operation' ;
Operation . prototype . checkActionDict = function ( grammar ) {
grammar . _checkTopDownActionDict ( this . typeName , this . name , this . actionDict ) ;
} ;
// Execute this operation on the CST node associated with `nodeWrapper` in the context of the given
// Semantics instance.
Operation . prototype . execute = function ( semantics , nodeWrapper ) {
// Look for a semantic action whose name matches the node's constructor name, which is either the
// name of a rule in the grammar, or '_terminal' (for a terminal node), or '_iter' (for an
// iteration node). In the latter case, the action function receives a single argument, which is
// an array containing all of the children of the CST node.
var actionFn = this . actionDict [ nodeWrapper . _node . ctorName ] ;
if ( actionFn ) {
return this . doAction ( semantics , nodeWrapper , actionFn , nodeWrapper . isIteration ( ) ) ;
}
// The action dictionary does not contain a semantic action for this specific type of node.
// If this is a nonterminal node and the programmer has provided a `_nonterminal` semantic
// action, we invoke it:
if ( nodeWrapper . isNonterminal ( ) ) {
actionFn = this . actionDict . _nonterminal ;
if ( actionFn ) {
return this . doAction ( semantics , nodeWrapper , actionFn , true ) ;
}
}
// Otherwise, we invoke the '_default' semantic action.
return this . doAction ( semantics , nodeWrapper , this . actionDict . _default , true ) ;
} ;
// Invoke `actionFn` on the CST node that corresponds to `nodeWrapper`, in the context of
// `semantics`. If `optPassChildrenAsArray` is truthy, `actionFn` will be called with a single
// argument, which is an array of wrappers. Otherwise, the number of arguments to `actionFn` will
// be equal to the number of children in the CST node.
Operation . prototype . doAction = function ( semantics , nodeWrapper , actionFn , optPassChildrenAsArray ) {
return optPassChildrenAsArray ?
actionFn . call ( nodeWrapper , nodeWrapper . _children ( ) ) :
actionFn . apply ( nodeWrapper , nodeWrapper . _children ( ) ) ;
} ;
// ----------------- Attribute -----------------
// Attributes are Operations whose results are memoized. This means that, for any given semantics,
// the semantic action for a CST node will be invoked no more than once.
2016-05-16 17:27:46 +00:00
function Attribute ( name , actionDict , builtInDefault ) {
2016-04-06 16:22:30 +00:00
this . name = name ;
this . formals = [ ] ;
this . actionDict = actionDict ;
2016-05-16 17:27:46 +00:00
this . builtInDefault = builtInDefault ;
2016-04-06 16:22:30 +00:00
}
inherits ( Attribute , Operation ) ;
Attribute . prototype . typeName = 'attribute' ;
Attribute . prototype . execute = function ( semantics , nodeWrapper ) {
var node = nodeWrapper . _node ;
var key = semantics . attributeKeys [ this . name ] ;
if ( ! node . hasOwnProperty ( key ) ) {
// The following is a super-send -- isn't JS beautiful? :/
node [ key ] = Operation . prototype . execute . call ( this , semantics , nodeWrapper ) ;
}
return node [ key ] ;
} ;
// --------------------------------------------------------------------
// Exports
// --------------------------------------------------------------------
module . exports = Semantics ;
} , { "./MatchResult" : 42 , "./common" : 48 , "./nodes" : 51 , "es6-symbol" : 15 , "inherits" : 33 } ] , 46 : [ function ( require , module , exports ) {
'use strict' ;
// --------------------------------------------------------------------
// Imports
// --------------------------------------------------------------------
2016-05-16 17:27:46 +00:00
var InputStream = require ( './InputStream' ) ;
2016-04-06 16:22:30 +00:00
var PosInfo = require ( './PosInfo' ) ;
var Trace = require ( './Trace' ) ;
var pexprs = require ( './pexprs' ) ;
2016-05-02 21:15:05 +00:00
2016-04-06 16:22:30 +00:00
// --------------------------------------------------------------------
// Private stuff
// --------------------------------------------------------------------
var RM _RIGHTMOST _FAILURE _POSITION = 0 ;
var RM _RIGHTMOST _FAILURES = 1 ;
var applySpaces = new pexprs . Apply ( 'spaces' ) ;
2016-05-02 21:15:05 +00:00
function State ( grammar , input , opts ) {
2016-04-06 16:22:30 +00:00
this . grammar = grammar ;
2016-05-02 21:15:05 +00:00
this . startExpr = this . _getStartExpr ( grammar , opts . startApplication ) ;
2016-05-16 17:27:46 +00:00
this . inputStream = new InputStream ( input ) ;
2016-04-06 16:22:30 +00:00
this . tracingEnabled = opts . trace || false ;
this . matchNodes = opts . matchNodes || false ;
this . init ( RM _RIGHTMOST _FAILURE _POSITION ) ;
}
State . prototype = {
init : function ( recordingMode ) {
2016-05-16 17:27:46 +00:00
this . posInfos = [ ] ;
2016-04-06 16:22:30 +00:00
this . bindings = [ ] ;
this . applicationStack = [ ] ;
this . inLexifiedContextStack = [ false ] ;
this . recordingMode = recordingMode ;
if ( recordingMode === RM _RIGHTMOST _FAILURE _POSITION ) {
this . rightmostFailurePosition = - 1 ;
} else if ( recordingMode === RM _RIGHTMOST _FAILURES ) {
// We always run in *rightmost failure position* recording mode before running in
// *rightmost failures* recording mode. And since the traces generated by each of
// these passes would be identical, there's no need to record it now if we have
// already recorded it in the first pass.
this . tracingEnabled = false ;
} else {
throw new Error ( 'invalid recording mode: ' + recordingMode ) ;
}
if ( this . isTracing ( ) ) {
this . trace = [ ] ;
}
} ,
enter : function ( app ) {
this . applicationStack . push ( app ) ;
this . inLexifiedContextStack . push ( false ) ;
} ,
exit : function ( ) {
this . applicationStack . pop ( ) ;
this . inLexifiedContextStack . pop ( ) ;
} ,
enterLexifiedContext : function ( ) {
this . inLexifiedContextStack . push ( true ) ;
} ,
exitLexifiedContext : function ( ) {
this . inLexifiedContextStack . pop ( ) ;
} ,
currentApplication : function ( ) {
return this . applicationStack [ this . applicationStack . length - 1 ] ;
} ,
2016-05-02 21:15:05 +00:00
inSyntacticContext : function ( ) {
2016-04-06 16:22:30 +00:00
if ( typeof this . inputStream . source !== 'string' ) {
return false ;
}
var currentApplication = this . currentApplication ( ) ;
2016-05-02 21:15:05 +00:00
if ( currentApplication ) {
return currentApplication . isSyntactic ( ) && ! this . inLexifiedContext ( ) ;
} else {
// The top-level context is syntactic if the start application is.
return this . startExpr . factors [ 0 ] . isSyntactic ( ) ;
}
2016-04-06 16:22:30 +00:00
} ,
inLexifiedContext : function ( ) {
return this . inLexifiedContextStack [ this . inLexifiedContextStack . length - 1 ] ;
} ,
skipSpaces : function ( ) {
var origFailuresInfo = this . getFailuresInfo ( ) ;
this . eval ( applySpaces ) ;
this . bindings . pop ( ) ;
this . restoreFailuresInfo ( origFailuresInfo ) ;
return this . inputStream . pos ;
} ,
skipSpacesIfInSyntacticContext : function ( ) {
return this . inSyntacticContext ( ) ?
this . skipSpaces ( ) :
this . inputStream . pos ;
} ,
2016-05-02 21:15:05 +00:00
maybeSkipSpacesBefore : function ( expr ) {
if ( expr instanceof pexprs . Apply && expr . isSyntactic ( ) ) {
return this . skipSpaces ( ) ;
} else if ( expr . allowsSkippingPrecedingSpace ( ) && expr !== applySpaces ) {
return this . skipSpacesIfInSyntacticContext ( ) ;
} else {
return this . inputStream . pos ;
}
} ,
2016-04-06 16:22:30 +00:00
truncateBindings : function ( newLength ) {
2016-08-07 19:41:10 +00:00
// TODO: is this really faster than setting the `length` property?
2016-04-06 16:22:30 +00:00
while ( this . bindings . length > newLength ) {
this . bindings . pop ( ) ;
}
} ,
getCurrentPosInfo : function ( ) {
return this . getPosInfo ( this . inputStream . pos ) ;
} ,
getPosInfo : function ( pos ) {
var posInfo = this . posInfos [ pos ] ;
return posInfo || ( this . posInfos [ pos ] = new PosInfo ( this ) ) ;
} ,
processFailure : function ( pos , expr ) {
if ( this . recordingMode === RM _RIGHTMOST _FAILURE _POSITION ) {
if ( pos > this . rightmostFailurePosition ) {
this . rightmostFailurePosition = pos ;
}
} else /* if (this.recordingMode === RM_RIGHTMOST_FAILURES) */
if ( pos === this . rightmostFailurePosition ) {
// We're only interested in failures at the rightmost failure position that haven't
// already been recorded.
this . addRightmostFailure ( expr . toFailure ( this . grammar ) , false ) ;
}
} ,
ensureRightmostFailures : function ( ) {
if ( ! this . rightmostFailures ) {
this . rightmostFailures = Object . create ( null ) ;
}
} ,
addRightmostFailure : function ( failure , shouldCloneIfNew ) {
this . ensureRightmostFailures ( ) ;
var key = failure . toKey ( ) ;
if ( ! this . rightmostFailures [ key ] ) {
this . rightmostFailures [ key ] = shouldCloneIfNew ? failure . clone ( ) : failure ;
} else if ( this . rightmostFailures [ key ] . isFluffy ( ) && ! failure . isFluffy ( ) ) {
this . rightmostFailures [ key ] . clearFluffy ( ) ;
}
} ,
addRightmostFailures : function ( failures , shouldCloneIfNew ) {
var self = this ;
Object . keys ( failures ) . forEach ( function ( key ) {
self . addRightmostFailure ( failures [ key ] , shouldCloneIfNew ) ;
} ) ;
} ,
cloneRightmostFailures : function ( ) {
if ( ! this . rightmostFailures ) {
return undefined ;
}
var ans = Object . create ( null ) ;
var self = this ;
Object . keys ( this . rightmostFailures ) . forEach ( function ( key ) {
ans [ key ] = self . rightmostFailures [ key ] . clone ( ) ;
} ) ;
return ans ;
} ,
getRightmostFailurePosition : function ( ) {
return this . rightmostFailurePosition ;
} ,
getFailures : function ( ) {
if ( this . recordingMode === RM _RIGHTMOST _FAILURE _POSITION ) {
// Rewind, then try to match the input again, recording failures.
this . init ( RM _RIGHTMOST _FAILURES ) ;
2016-05-02 21:15:05 +00:00
this . evalFromStart ( ) ;
2016-04-06 16:22:30 +00:00
}
this . ensureRightmostFailures ( ) ;
var self = this ;
return Object . keys ( this . rightmostFailures ) . map ( function ( key ) {
return self . rightmostFailures [ key ] ;
} ) ;
} ,
// Returns the memoized trace entry for `expr` at `pos`, if one exists, `null` otherwise.
getMemoizedTraceEntry : function ( pos , expr ) {
var posInfo = this . posInfos [ pos ] ;
if ( posInfo && expr . ruleName ) {
var memoRec = posInfo . memo [ expr . toMemoKey ( ) ] ;
2016-08-07 19:41:10 +00:00
if ( memoRec ) {
return memoRec . traceEntry ;
2016-04-06 16:22:30 +00:00
}
}
return null ;
} ,
// Returns a new trace entry, with the currently active trace array as its children.
2016-05-02 21:15:05 +00:00
getTraceEntry : function ( pos , expr , succeeded , bindings ) {
2016-08-07 19:41:10 +00:00
var memoEntry = this . getMemoizedTraceEntry ( pos , expr ) ;
return memoEntry ? memoEntry . cloneWithExpr ( expr )
: new Trace ( this . inputStream , pos , expr , succeeded , bindings , this . trace ) ;
2016-04-06 16:22:30 +00:00
} ,
isTracing : function ( ) {
return this . tracingEnabled ;
} ,
useMemoizedResult : function ( memoRec ) {
if ( this . isTracing ( ) ) {
this . trace . push ( memoRec . traceEntry ) ;
}
if ( this . recordingMode === RM _RIGHTMOST _FAILURES && memoRec . failuresAtRightmostPosition ) {
this . addRightmostFailures ( memoRec . failuresAtRightmostPosition , true ) ;
}
if ( memoRec . value ) {
this . inputStream . pos = memoRec . pos ;
this . bindings . push ( memoRec . value ) ;
return true ;
}
return false ;
} ,
// Evaluate `expr` and return `true` if it succeeded, `false` otherwise. On success, `bindings`
// will have `expr.getArity()` more elements than before, and the input stream's position may
// have increased. On failure, `bindings` and position will be unchanged.
eval : function ( expr ) {
var inputStream = this . inputStream ;
var origNumBindings = this . bindings . length ;
if ( this . recordingMode === RM _RIGHTMOST _FAILURES ) {
var origFailures = this . rightmostFailures ;
this . rightmostFailures = undefined ;
}
2016-05-02 21:15:05 +00:00
var origPos = inputStream . pos ;
var memoPos = this . maybeSkipSpacesBefore ( expr ) ;
2016-04-06 16:22:30 +00:00
if ( this . isTracing ( ) ) {
var origTrace = this . trace ;
this . trace = [ ] ;
}
// Do the actual evaluation.
var ans = expr . eval ( this ) ;
if ( this . isTracing ( ) ) {
2016-05-02 21:15:05 +00:00
var bindings = this . bindings . slice ( origNumBindings ) ;
var traceEntry = this . getTraceEntry ( memoPos , expr , ans , bindings ) ;
traceEntry . isImplicitSpaces = expr === applySpaces ;
traceEntry . isRootNode = expr === this . startExpr ;
2016-04-06 16:22:30 +00:00
origTrace . push ( traceEntry ) ;
this . trace = origTrace ;
}
if ( ans ) {
if ( this . rightmostFailures &&
( inputStream . pos === this . rightmostFailurePosition ||
this . skipSpacesIfInSyntacticContext ( ) === this . rightmostFailurePosition ) ) {
var self = this ;
Object . keys ( this . rightmostFailures ) . forEach ( function ( key ) {
self . rightmostFailures [ key ] . makeFluffy ( ) ;
} ) ;
}
} else {
// Reset the position and the bindings.
inputStream . pos = origPos ;
this . truncateBindings ( origNumBindings ) ;
}
if ( this . recordingMode === RM _RIGHTMOST _FAILURES && origFailures ) {
this . addRightmostFailures ( origFailures , false ) ;
}
return ans ;
} ,
2016-05-02 21:15:05 +00:00
// Return the starting expression for this grammar. If `optStartApplication` is specified, it
// is a string expressing a rule application in the grammar. If not specified, the grammar's
// default start rule will be used.
_getStartExpr : function ( grammar , optStartApplication ) {
var applicationStr = optStartApplication || grammar . defaultStartRule ;
if ( ! applicationStr ) {
throw new Error ( 'Missing start rule argument -- the grammar has no default start rule.' ) ;
}
var startApp = grammar . parseApplication ( applicationStr ) ;
return new pexprs . Seq ( [ startApp , pexprs . end ] ) ;
} ,
evalFromStart : function ( ) {
this . eval ( this . startExpr ) ;
} ,
2016-04-06 16:22:30 +00:00
getFailuresInfo : function ( ) {
if ( this . recordingMode === RM _RIGHTMOST _FAILURE _POSITION ) {
return this . rightmostFailurePosition ;
} else /* if (this.recordingMode === RM_RIGHTMOST_FAILURES) */ {
return this . rightmostFailures ;
}
} ,
restoreFailuresInfo : function ( failuresInfo ) {
if ( this . recordingMode === RM _RIGHTMOST _FAILURE _POSITION ) {
this . rightmostFailurePosition = failuresInfo ;
} else /* if (this.recordingMode === RM_RIGHTMOST_FAILURES) */ {
this . rightmostFailures = failuresInfo ;
}
2016-05-02 21:15:05 +00:00
}
2016-04-06 16:22:30 +00:00
} ;
// --------------------------------------------------------------------
// Exports
// --------------------------------------------------------------------
module . exports = State ;
2016-05-16 17:27:46 +00:00
} , { "./InputStream" : 40 , "./PosInfo" : 44 , "./Trace" : 47 , "./pexprs" : 67 } ] , 47 : [ function ( require , module , exports ) {
2016-04-06 16:22:30 +00:00
'use strict' ;
// --------------------------------------------------------------------
// Imports
// --------------------------------------------------------------------
var Interval = require ( './Interval' ) ;
var common = require ( './common' ) ;
// --------------------------------------------------------------------
// Private stuff
// --------------------------------------------------------------------
// Unicode characters that are used in the `toString` output.
var BALLOT _X = '\u2717' ;
var CHECK _MARK = '\u2713' ;
var DOT _OPERATOR = '\u22C5' ;
var RIGHTWARDS _DOUBLE _ARROW = '\u21D2' ;
var SYMBOL _FOR _HORIZONTAL _TABULATION = '\u2409' ;
var SYMBOL _FOR _LINE _FEED = '\u240A' ;
var SYMBOL _FOR _CARRIAGE _RETURN = '\u240D' ;
function spaces ( n ) {
return common . repeat ( ' ' , n ) . join ( '' ) ;
}
// Return a string representation of a portion of `inputStream` at offset `pos`.
// The result will contain exactly `len` characters.
function getInputExcerpt ( inputStream , pos , len ) {
var excerpt = asEscapedString ( inputStream . sourceSlice ( pos , pos + len ) ) ;
// Pad the output if necessary.
if ( excerpt . length < len ) {
return excerpt + common . repeat ( ' ' , len - excerpt . length ) . join ( '' ) ;
}
return excerpt ;
}
function asEscapedString ( obj ) {
if ( typeof obj === 'string' ) {
// Replace non-printable characters with visible symbols.
return obj
. replace ( / /g , DOT _OPERATOR )
. replace ( /\t/g , SYMBOL _FOR _HORIZONTAL _TABULATION )
. replace ( /\n/g , SYMBOL _FOR _LINE _FEED )
. replace ( /\r/g , SYMBOL _FOR _CARRIAGE _RETURN ) ;
}
return String ( obj ) ;
}
// ----------------- Trace -----------------
2016-05-02 21:15:05 +00:00
function Trace ( inputStream , pos , expr , succeeded , bindings , optChildren ) {
this . inputStream = inputStream ;
this . pos = pos ;
this . interval = new Interval ( inputStream , pos , inputStream . pos ) ;
2016-04-06 16:22:30 +00:00
this . expr = expr ;
2016-05-02 21:15:05 +00:00
this . succeeded = succeeded ;
this . bindings = bindings ;
this . children = optChildren || [ ] ;
this . isImplicitSpaces = false ;
2016-08-07 19:41:10 +00:00
this . isLeftRecursive = false ;
2016-05-02 21:15:05 +00:00
this . isMemoized = false ;
this . isRootNode = false ;
2016-04-06 16:22:30 +00:00
}
// A value that can be returned from visitor functions to indicate that a
// node should not be recursed into.
Trace . prototype . SKIP = { } ;
Object . defineProperty ( Trace . prototype , 'displayString' , {
get : function ( ) { return this . expr . toDisplayString ( ) ; }
} ) ;
Trace . prototype . cloneWithExpr = function ( expr ) {
2016-05-02 21:15:05 +00:00
var ans = new Trace (
this . inputStream , this . pos , expr , this . succeeded , this . bindings , this . children ) ;
2016-08-07 19:41:10 +00:00
ans . isLeftRecursive = this . isLeftRecursive ;
2016-05-02 21:15:05 +00:00
ans . isRootNode = this . isRootNode ;
2016-08-07 19:41:10 +00:00
ans . isMemoized = true ;
2016-04-06 16:22:30 +00:00
return ans ;
} ;
// Recursively traverse this trace node and all its descendents, calling a visitor function
// for each node that is visited. If `vistorObjOrFn` is an object, then its 'enter' property
// is a function to call before visiting the children of a node, and its 'exit' property is
// a function to call afterwards. If `visitorObjOrFn` is a function, it represents the 'enter'
// function.
//
// The functions are called with three arguments: the Trace node, its parent Trace, and a number
// representing the depth of the node in the tree. (The root node has depth 0.) `optThisArg`, if
// specified, is the value to use for `this` when executing the visitor functions.
Trace . prototype . walk = function ( visitorObjOrFn , optThisArg ) {
var visitor = visitorObjOrFn ;
if ( typeof visitor === 'function' ) {
visitor = { enter : visitor } ;
}
2016-05-02 21:15:05 +00:00
function _walk ( node , parent , depth ) {
2016-04-06 16:22:30 +00:00
var recurse = true ;
if ( visitor . enter ) {
if ( visitor . enter . call ( optThisArg , node , parent , depth ) === Trace . prototype . SKIP ) {
recurse = false ;
}
}
if ( recurse ) {
2016-08-07 19:41:10 +00:00
node . children . forEach ( function ( child , i ) {
var nextChild = node . children [ i + 1 ] ;
if ( nextChild && nextChild . expr === child . expr && nextChild . pos === child . pos ) {
// Skip this child -- it is an intermediate left-recursive result.
common . assert ( node . isLeftRecursive ) ;
} else {
_walk ( child , node , depth + 1 ) ;
}
2016-04-06 16:22:30 +00:00
} ) ;
if ( visitor . exit ) {
visitor . exit . call ( optThisArg , node , parent , depth ) ;
}
}
2016-05-02 21:15:05 +00:00
}
if ( this . isRootNode ) {
// Don't visit the root node itself, only its children.
this . children . forEach ( function ( c ) { _walk ( c , null , 0 ) ; } ) ;
} else {
_walk ( this , null , 0 ) ;
}
2016-04-06 16:22:30 +00:00
} ;
// Return a string representation of the trace.
// Sample:
// 12⋅+⋅2⋅*⋅3 ✓ exp ⇒ "12"
// 12⋅+⋅2⋅*⋅3 ✓ addExp (LR) ⇒ "12"
// 12⋅+⋅2⋅*⋅3 ✗ addExp_plus
Trace . prototype . toString = function ( ) {
var sb = new common . StringBuffer ( ) ;
this . walk ( function ( node , parent , depth ) {
2016-05-02 21:15:05 +00:00
if ( ! node ) {
return this . SKIP ;
}
2016-04-06 16:22:30 +00:00
var ctorName = node . expr . constructor . name ;
2016-05-02 21:15:05 +00:00
// Don't print anything for Alt nodes.
2016-04-06 16:22:30 +00:00
if ( ctorName === 'Alt' ) {
2016-05-02 21:15:05 +00:00
return ; // eslint-disable-line consistent-return
2016-04-06 16:22:30 +00:00
}
sb . append ( getInputExcerpt ( node . inputStream , node . pos , 10 ) + spaces ( depth * 2 + 1 ) ) ;
sb . append ( ( node . succeeded ? CHECK _MARK : BALLOT _X ) + ' ' + node . displayString ) ;
2016-08-07 19:41:10 +00:00
if ( node . isLeftRecursive ) {
2016-04-06 16:22:30 +00:00
sb . append ( ' (LR)' ) ;
}
if ( node . succeeded ) {
var contents = asEscapedString ( node . interval . contents ) ;
sb . append ( ' ' + RIGHTWARDS _DOUBLE _ARROW + ' ' ) ;
sb . append ( typeof contents === 'string' ? '"' + contents + '"' : contents ) ;
}
sb . append ( '\n' ) ;
2016-05-02 21:15:05 +00:00
} . bind ( this ) ) ;
2016-04-06 16:22:30 +00:00
return sb . contents ( ) ;
} ;
// --------------------------------------------------------------------
// Exports
// --------------------------------------------------------------------
module . exports = Trace ;
} , { "./Interval" : 41 , "./common" : 48 } ] , 48 : [ function ( require , module , exports ) {
'use strict' ;
// --------------------------------------------------------------------
// Imports
// --------------------------------------------------------------------
var extend = require ( 'util-extend' ) ;
// --------------------------------------------------------------------
// Private Stuff
// --------------------------------------------------------------------
// Helpers
var escapeStringFor = { } ;
for ( var c = 0 ; c < 128 ; c ++ ) {
escapeStringFor [ c ] = String . fromCharCode ( c ) ;
}
escapeStringFor [ "'" . charCodeAt ( 0 ) ] = "\\'" ;
escapeStringFor [ '"' . charCodeAt ( 0 ) ] = '\\"' ;
escapeStringFor [ '\\' . charCodeAt ( 0 ) ] = '\\\\' ;
escapeStringFor [ '\b' . charCodeAt ( 0 ) ] = '\\b' ;
escapeStringFor [ '\f' . charCodeAt ( 0 ) ] = '\\f' ;
escapeStringFor [ '\n' . charCodeAt ( 0 ) ] = '\\n' ;
escapeStringFor [ '\r' . charCodeAt ( 0 ) ] = '\\r' ;
escapeStringFor [ '\t' . charCodeAt ( 0 ) ] = '\\t' ;
escapeStringFor [ '\u000b' . charCodeAt ( 0 ) ] = '\\v' ;
// --------------------------------------------------------------------
// Exports
// --------------------------------------------------------------------
2017-02-20 22:19:56 +00:00
exports . abstract = function ( ) {
throw new Error (
'this method is abstract! ' +
2016-04-06 16:22:30 +00:00
'(it has no implementation in class ' + this . constructor . name + ')' ) ;
} ;
exports . assert = function ( cond , message ) {
if ( ! cond ) {
throw new Error ( message ) ;
}
} ;
// Define a lazily-computed, non-enumerable property named `propName`
// on the object `obj`. `getterFn` will be called to compute the value the
// first time the property is accessed.
exports . defineLazyProperty = function ( obj , propName , getterFn ) {
var memo ;
Object . defineProperty ( obj , propName , {
get : function ( ) {
if ( ! memo ) {
memo = getterFn . call ( this ) ;
}
return memo ;
}
} ) ;
} ;
exports . clone = function ( obj ) {
if ( obj ) {
return extend ( { } , obj ) ;
}
return obj ;
} ;
exports . extend = extend ;
exports . repeatFn = function ( fn , n ) {
var arr = [ ] ;
while ( n -- > 0 ) {
arr . push ( fn ( ) ) ;
}
return arr ;
} ;
exports . repeatStr = function ( str , n ) {
return new Array ( n + 1 ) . join ( str ) ;
} ;
exports . repeat = function ( x , n ) {
return exports . repeatFn ( function ( ) { return x ; } , n ) ;
} ;
exports . getDuplicates = function ( array ) {
var duplicates = [ ] ;
for ( var idx = 0 ; idx < array . length ; idx ++ ) {
var x = array [ idx ] ;
if ( array . lastIndexOf ( x ) !== idx && duplicates . indexOf ( x ) < 0 ) {
duplicates . push ( x ) ;
}
}
return duplicates ;
} ;
2016-05-02 21:15:05 +00:00
exports . copyWithoutDuplicates = function ( array ) {
var noDuplicates = [ ] ;
array . forEach ( function ( entry ) {
if ( noDuplicates . indexOf ( entry ) < 0 ) {
noDuplicates . push ( entry ) ;
}
} ) ;
return noDuplicates ;
} ;
2016-04-06 16:22:30 +00:00
exports . isSyntactic = function ( ruleName ) {
var firstChar = ruleName [ 0 ] ;
return firstChar === firstChar . toUpperCase ( ) ;
} ;
exports . isLexical = function ( ruleName ) {
return ! exports . isSyntactic ( ruleName ) ;
} ;
exports . padLeft = function ( str , len , optChar ) {
var ch = optChar || ' ' ;
if ( str . length < len ) {
return exports . repeatStr ( ch , len - str . length ) + str ;
}
return str ;
} ;
// StringBuffer
exports . StringBuffer = function ( ) {
this . strings = [ ] ;
} ;
exports . StringBuffer . prototype . append = function ( str ) {
this . strings . push ( str ) ;
} ;
exports . StringBuffer . prototype . contents = function ( ) {
return this . strings . join ( '' ) ;
} ;
// Character escaping and unescaping
exports . escapeChar = function ( c , optDelim ) {
var charCode = c . charCodeAt ( 0 ) ;
if ( ( c === '"' || c === "'" ) && optDelim && c !== optDelim ) {
return c ;
} else if ( charCode < 128 ) {
return escapeStringFor [ charCode ] ;
} else if ( 128 <= charCode && charCode < 256 ) {
return '\\x' + exports . padLeft ( charCode . toString ( 16 ) , 2 , '0' ) ;
} else {
return '\\u' + exports . padLeft ( charCode . toString ( 16 ) , 4 , '0' ) ;
}
} ;
exports . unescapeChar = function ( s ) {
if ( s . charAt ( 0 ) === '\\' ) {
switch ( s . charAt ( 1 ) ) {
case 'b' : return '\b' ;
case 'f' : return '\f' ;
case 'n' : return '\n' ;
case 'r' : return '\r' ;
case 't' : return '\t' ;
case 'v' : return '\v' ;
case 'x' : return String . fromCharCode ( parseInt ( s . substring ( 2 , 4 ) , 16 ) ) ;
case 'u' : return String . fromCharCode ( parseInt ( s . substring ( 2 , 6 ) , 16 ) ) ;
default : return s . charAt ( 1 ) ;
}
} else {
return s ;
}
} ;
// Helper for producing a description of an unknown object in a safe way.
// Especially useful for error messages where an unexpected type of object was encountered.
exports . unexpectedObjToString = function ( obj ) {
if ( obj == null ) {
return String ( obj ) ;
}
var baseToString = Object . prototype . toString . call ( obj ) ;
try {
var typeName ;
if ( obj . constructor && obj . constructor . name ) {
typeName = obj . constructor . name ;
} else if ( baseToString . indexOf ( '[object ' ) === 0 ) {
typeName = baseToString . slice ( 8 , - 1 ) ; // Extract e.g. "Array" from "[object Array]".
} else {
typeName = typeof obj ;
}
return typeName + ': ' + JSON . stringify ( String ( obj ) ) ;
} catch ( e ) {
return baseToString ;
}
} ;
} , { "util-extend" : 35 } ] , 49 : [ function ( require , module , exports ) {
'use strict' ;
// --------------------------------------------------------------------
// Imports
// --------------------------------------------------------------------
var Namespace = require ( './Namespace' ) ;
// --------------------------------------------------------------------
// Private stuff
// --------------------------------------------------------------------
function createError ( message , optInterval ) {
var e ;
if ( optInterval ) {
e = new Error ( optInterval . getLineAndColumnMessage ( ) + message ) ;
e . shortMessage = message ;
e . interval = optInterval ;
} else {
e = new Error ( message ) ;
}
return e ;
}
// ----------------- errors about intervals -----------------
function intervalSourcesDontMatch ( ) {
return createError ( "Interval sources don't match" ) ;
}
// ----------------- errors about grammars -----------------
// Grammar syntax error
function grammarSyntaxError ( matchFailure ) {
var e = new Error ( ) ;
Object . defineProperty ( e , 'message' , { get : function ( ) { return matchFailure . message ; } } ) ;
Object . defineProperty ( e , 'shortMessage' , { get : function ( ) {
return 'Expected ' + matchFailure . getExpectedText ( ) ;
} } ) ;
e . interval = matchFailure . getInterval ( ) ;
return e ;
}
// Undeclared grammar
function undeclaredGrammar ( grammarName , namespace , interval ) {
var message = namespace ?
'Grammar ' + grammarName + ' is not declared in namespace ' + Namespace . toString ( namespace ) :
'Undeclared grammar ' + grammarName ;
return createError ( message , interval ) ;
}
// Duplicate grammar declaration
function duplicateGrammarDeclaration ( grammar , namespace ) {
return createError ( 'Grammar ' + grammar . name + ' is already declared in this namespace' ) ;
}
// ----------------- rules -----------------
// Undeclared rule
function undeclaredRule ( ruleName , grammarName , optInterval ) {
return createError (
'Rule ' + ruleName + ' is not declared in grammar ' + grammarName ,
optInterval ) ;
}
// Cannot override undeclared rule
function cannotOverrideUndeclaredRule ( ruleName , grammarName , body ) {
return createError (
'Cannot override rule ' + ruleName + ' because it is not declared in ' + grammarName ,
body . definitionInterval ) ;
}
// Cannot extend undeclared rule
function cannotExtendUndeclaredRule ( ruleName , grammarName , body ) {
return createError (
'Cannot extend rule ' + ruleName + ' because it is not declared in ' + grammarName ,
body . definitionInterval ) ;
}
// Duplicate rule declaration
function duplicateRuleDeclaration ( ruleName , offendingGrammarName , declGrammarName , body ) {
var message = "Duplicate declaration for rule '" + ruleName +
"' in grammar '" + offendingGrammarName + "'" ;
if ( offendingGrammarName !== declGrammarName ) {
message += " (originally declared in '" + declGrammarName + "')" ;
}
return createError ( message , body . definitionInterval ) ;
}
// Wrong number of parameters
function wrongNumberOfParameters ( ruleName , expected , actual , body ) {
return createError (
'Wrong number of parameters for rule ' + ruleName +
' (expected ' + expected + ', got ' + actual + ')' ,
body && body . definitionInterval ) ;
}
// Wrong number of arguments
function wrongNumberOfArguments ( ruleName , expected , actual , expr ) {
return createError (
'Wrong number of arguments for rule ' + ruleName +
' (expected ' + expected + ', got ' + actual + ')' ,
expr . interval ) ;
}
// Duplicate parameter names
function duplicateParameterNames ( ruleName , duplicates , body ) {
return createError (
'Duplicate parameter names in rule ' + ruleName + ': ' + duplicates . join ( ',' ) ,
body . definitionInterval ) ;
}
// Invalid parameter expression
function invalidParameter ( ruleName , expr ) {
return createError (
'Invalid parameter to rule ' + ruleName + ': ' + expr + ' has arity ' + expr . getArity ( ) +
', but parameter expressions ' + 'must have arity 1' ,
expr . interval ) ;
}
// Application of syntactic rule from lexical rule
function applicationOfSyntacticRuleFromLexicalContext ( ruleName , applyExpr ) {
return createError (
'Cannot apply syntactic rule ' + ruleName + ' from here (inside a lexical context)' ,
applyExpr . interval ) ;
}
// ----------------- Kleene operators -----------------
function kleeneExprHasNullableOperand ( kleeneExpr ) {
return createError (
'Nullable expression ' + kleeneExpr . expr . interval . contents + " is not allowed inside '" +
kleeneExpr . operator + "' (possible infinite loop)" ,
kleeneExpr . expr . interval ) ;
}
// ----------------- arity -----------------
function inconsistentArity ( ruleName , expected , actual , expr ) {
return createError (
'Rule ' + ruleName + ' involves an alternation which has inconsistent arity ' +
'(expected ' + expected + ', got ' + actual + ')' ,
expr . interval ) ;
}
// ----------------- properties -----------------
function duplicatePropertyNames ( duplicates ) {
return createError ( 'Object pattern has duplicate property names: ' + duplicates . join ( ', ' ) ) ;
}
// ----------------- constructors -----------------
function invalidConstructorCall ( grammar , ctorName , children ) {
return createError (
'Attempt to invoke constructor ' + ctorName + ' with invalid or unexpected arguments' ) ;
}
// ----------------- convenience -----------------
function multipleErrors ( errors ) {
var messages = errors . map ( function ( e ) { return e . message ; } ) ;
return createError (
[ 'Errors:' ] . concat ( messages ) . join ( '\n- ' ) ,
errors [ 0 ] . interval ) ;
}
// --------------------------------------------------------------------
// Exports
// --------------------------------------------------------------------
module . exports = {
applicationOfSyntacticRuleFromLexicalContext : applicationOfSyntacticRuleFromLexicalContext ,
cannotExtendUndeclaredRule : cannotExtendUndeclaredRule ,
cannotOverrideUndeclaredRule : cannotOverrideUndeclaredRule ,
duplicateGrammarDeclaration : duplicateGrammarDeclaration ,
duplicateParameterNames : duplicateParameterNames ,
duplicatePropertyNames : duplicatePropertyNames ,
duplicateRuleDeclaration : duplicateRuleDeclaration ,
inconsistentArity : inconsistentArity ,
intervalSourcesDontMatch : intervalSourcesDontMatch ,
invalidConstructorCall : invalidConstructorCall ,
invalidParameter : invalidParameter ,
grammarSyntaxError : grammarSyntaxError ,
kleeneExprHasNullableOperand : kleeneExprHasNullableOperand ,
undeclaredGrammar : undeclaredGrammar ,
undeclaredRule : undeclaredRule ,
wrongNumberOfArguments : wrongNumberOfArguments ,
wrongNumberOfParameters : wrongNumberOfParameters ,
throwErrors : function ( errors ) {
if ( errors . length === 1 ) {
throw errors [ 0 ] ;
}
if ( errors . length > 1 ) {
throw multipleErrors ( errors ) ;
}
}
} ;
} , { "./Namespace" : 43 } ] , 50 : [ function ( require , module , exports ) {
/* global document, XMLHttpRequest */
'use strict' ;
// --------------------------------------------------------------------
// Imports
// --------------------------------------------------------------------
var Builder = require ( './Builder' ) ;
var Grammar = require ( './Grammar' ) ;
var Namespace = require ( './Namespace' ) ;
var common = require ( './common' ) ;
var errors = require ( './errors' ) ;
var pexprs = require ( './pexprs' ) ;
var util = require ( './util' ) ;
var isBuffer = require ( 'is-buffer' ) ;
// --------------------------------------------------------------------
// Private stuff
// --------------------------------------------------------------------
// The metagrammar, i.e. the grammar for Ohm grammars. Initialized at the
// bottom of this file because loading the grammar requires Ohm itself.
var ohmGrammar ;
// An object which makes it possible to stub out the document API for testing.
var documentInterface = {
querySelector : function ( sel ) { return document . querySelector ( sel ) ; } ,
querySelectorAll : function ( sel ) { return document . querySelectorAll ( sel ) ; }
} ;
// Check if `obj` is a DOM element.
function isElement ( obj ) {
return ! ! ( obj && obj . nodeType === 1 ) ;
}
function isUndefined ( obj ) {
return obj === void 0 ;
}
var MAX _ARRAY _INDEX = Math . pow ( 2 , 53 ) - 1 ;
function isArrayLike ( obj ) {
if ( obj == null ) {
return false ;
}
var length = obj . length ;
return typeof length === 'number' && length >= 0 && length <= MAX _ARRAY _INDEX ;
}
// TODO: just use the jQuery thing
function load ( url ) {
var req = new XMLHttpRequest ( ) ;
req . open ( 'GET' , url , false ) ;
try {
req . send ( ) ;
if ( req . status === 0 || req . status === 200 ) {
return req . responseText ;
}
} catch ( e ) { }
throw new Error ( 'unable to load url ' + url ) ;
}
// Returns a Grammar instance (i.e., an object with a `match` method) for
// `tree`, which is the concrete syntax tree of a user-written grammar.
// The grammar will be assigned into `namespace` under the name of the grammar
// as specified in the source.
function buildGrammar ( match , namespace , optOhmGrammarForTesting ) {
var builder = new Builder ( ) ;
var decl ;
var currentRuleName ;
var currentRuleFormals ;
var overriding = false ;
var metaGrammar = optOhmGrammarForTesting || ohmGrammar ;
// A visitor that produces a Grammar instance from the CST.
var helpers = metaGrammar . semantics ( ) . addOperation ( 'visit' , {
Grammar : function ( n , s , open , rs , close ) {
var grammarName = n . visit ( ) ;
decl = builder . newGrammar ( grammarName , namespace ) ;
s . visit ( ) ;
rs . visit ( ) ;
var g = decl . build ( ) ;
g . definitionInterval = this . interval . trimmed ( ) ;
if ( grammarName in namespace ) {
throw errors . duplicateGrammarDeclaration ( g , namespace ) ;
}
namespace [ grammarName ] = g ;
return g ;
} ,
SuperGrammar : function ( _ , n ) {
var superGrammarName = n . visit ( ) ;
if ( superGrammarName === 'null' ) {
decl . withSuperGrammar ( null ) ;
} else {
if ( ! namespace || ! ( superGrammarName in namespace ) ) {
throw errors . undeclaredGrammar ( superGrammarName , namespace , n . interval ) ;
}
decl . withSuperGrammar ( namespace [ superGrammarName ] ) ;
}
} ,
2016-05-16 17:27:46 +00:00
Rule _define : function ( n , fs , d , _ , b ) {
2016-04-06 16:22:30 +00:00
currentRuleName = n . visit ( ) ;
currentRuleFormals = fs . visit ( ) [ 0 ] || [ ] ;
// If there is no default start rule yet, set it now. This must be done before visiting
// the body, because it might contain an inline rule definition.
if ( ! decl . defaultStartRule && decl . ensureSuperGrammar ( ) !== Grammar . ProtoBuiltInRules ) {
decl . withDefaultStartRule ( currentRuleName ) ;
}
var body = b . visit ( ) ;
body . definitionInterval = this . interval . trimmed ( ) ;
var description = d . visit ( ) [ 0 ] ;
return decl . define ( currentRuleName , currentRuleFormals , body , description ) ;
} ,
2016-05-16 17:27:46 +00:00
Rule _override : function ( n , fs , _ , b ) {
2016-04-06 16:22:30 +00:00
currentRuleName = n . visit ( ) ;
currentRuleFormals = fs . visit ( ) [ 0 ] || [ ] ;
overriding = true ;
var body = b . visit ( ) ;
body . definitionInterval = this . interval . trimmed ( ) ;
var ans = decl . override ( currentRuleName , currentRuleFormals , body ) ;
overriding = false ;
return ans ;
} ,
2016-05-16 17:27:46 +00:00
Rule _extend : function ( n , fs , _ , b ) {
2016-04-06 16:22:30 +00:00
currentRuleName = n . visit ( ) ;
currentRuleFormals = fs . visit ( ) [ 0 ] || [ ] ;
var body = b . visit ( ) ;
var ans = decl . extend ( currentRuleName , currentRuleFormals , body ) ;
decl . ruleBodies [ currentRuleName ] . definitionInterval = this . interval . trimmed ( ) ;
return ans ;
} ,
2016-08-07 19:41:10 +00:00
RuleBody : function ( _ , term , _bars , terms ) {
var args = [ term . visit ( ) ] . concat ( terms . visit ( ) ) ;
2016-05-16 17:27:46 +00:00
return builder . alt . apply ( builder , args ) . withInterval ( this . interval ) ;
} ,
2016-04-06 16:22:30 +00:00
Formals : function ( opointy , fs , cpointy ) {
return fs . visit ( ) ;
} ,
Params : function ( opointy , ps , cpointy ) {
return ps . visit ( ) ;
} ,
2016-08-07 19:41:10 +00:00
Alt : function ( seq , _ , seqs ) {
var args = [ seq . visit ( ) ] . concat ( seqs . visit ( ) ) ;
2016-04-06 16:22:30 +00:00
return builder . alt . apply ( builder , args ) . withInterval ( this . interval ) ;
} ,
2016-05-16 17:27:46 +00:00
TopLevelTerm _inline : function ( b , n ) {
2016-04-06 16:22:30 +00:00
var inlineRuleName = currentRuleName + '_' + n . visit ( ) ;
var body = b . visit ( ) ;
body . definitionInterval = this . interval . trimmed ( ) ;
var isNewRuleDeclaration =
! ( decl . superGrammar && decl . superGrammar . ruleBodies [ inlineRuleName ] ) ;
if ( overriding && ! isNewRuleDeclaration ) {
decl . override ( inlineRuleName , currentRuleFormals , body ) ;
} else {
decl . define ( inlineRuleName , currentRuleFormals , body ) ;
}
var params = currentRuleFormals . map ( function ( formal ) { return builder . app ( formal ) ; } ) ;
return builder . app ( inlineRuleName , params ) . withInterval ( body . interval ) ;
} ,
Seq : function ( expr ) {
return builder . seq . apply ( builder , expr . visit ( ) ) . withInterval ( this . interval ) ;
} ,
Iter _star : function ( x , _ ) {
return builder . star ( x . visit ( ) ) . withInterval ( this . interval ) ;
} ,
Iter _plus : function ( x , _ ) {
return builder . plus ( x . visit ( ) ) . withInterval ( this . interval ) ;
} ,
Iter _opt : function ( x , _ ) {
return builder . opt ( x . visit ( ) ) . withInterval ( this . interval ) ;
} ,
Pred _not : function ( _ , x ) {
return builder . not ( x . visit ( ) ) . withInterval ( this . interval ) ;
} ,
Pred _lookahead : function ( _ , x ) {
2016-08-07 19:41:10 +00:00
return builder . la ( x . visit ( ) ) . withInterval ( this . interval ) ;
2016-04-06 16:22:30 +00:00
} ,
2016-05-16 17:27:46 +00:00
Lex _lex : function ( _ , x ) {
2016-04-06 16:22:30 +00:00
return builder . lex ( x . visit ( ) ) . withInterval ( this . interval ) ;
} ,
Base _application : function ( rule , ps ) {
return builder . app ( rule . visit ( ) , ps . visit ( ) [ 0 ] || [ ] ) . withInterval ( this . interval ) ;
} ,
Base _range : function ( from , _ , to ) {
return builder . range ( from . visit ( ) , to . visit ( ) ) . withInterval ( this . interval ) ;
} ,
2016-05-16 17:27:46 +00:00
Base _terminal : function ( expr ) {
return builder . terminal ( expr . visit ( ) ) . withInterval ( this . interval ) ;
2016-04-06 16:22:30 +00:00
} ,
Base _paren : function ( open , x , close ) {
return x . visit ( ) ;
} ,
ruleDescr : function ( open , t , close ) {
return t . visit ( ) ;
} ,
ruleDescrText : function ( _ ) {
return this . interval . contents . trim ( ) ;
} ,
caseName : function ( _ , space1 , n , space2 , end ) {
return n . visit ( ) ;
} ,
name : function ( first , rest ) {
return this . interval . contents ;
} ,
nameFirst : function ( expr ) { } ,
nameRest : function ( expr ) { } ,
2016-05-16 17:27:46 +00:00
terminal : function ( open , cs , close ) {
2016-04-06 16:22:30 +00:00
return cs . visit ( ) . map ( function ( c ) { return common . unescapeChar ( c ) ; } ) . join ( '' ) ;
} ,
2016-05-16 17:27:46 +00:00
terminalChar : function ( _ ) {
2016-04-06 16:22:30 +00:00
return this . interval . contents ;
} ,
escapeChar : function ( _ ) {
return this . interval . contents ;
} ,
NonemptyListOf : function ( x , _ , xs ) {
return [ x . visit ( ) ] . concat ( xs . visit ( ) ) ;
} ,
EmptyListOf : function ( ) {
return [ ] ;
2016-05-02 21:15:05 +00:00
} ,
_terminal : function ( ) {
return this . primitiveValue ;
2016-04-06 16:22:30 +00:00
}
} ) ;
return helpers ( match ) . visit ( ) ;
}
function compileAndLoad ( source , namespace ) {
var m = ohmGrammar . match ( source , 'Grammars' ) ;
if ( m . failed ( ) ) {
throw errors . grammarSyntaxError ( m ) ;
}
return buildGrammar ( m , namespace ) ;
}
// Return the contents of a script element, fetching it via XHR if necessary.
function getScriptElementContents ( el ) {
if ( ! isElement ( el ) ) {
throw new TypeError ( 'Expected a DOM Node, got ' + common . unexpectedObjToString ( el ) ) ;
}
if ( el . type !== 'text/ohm-js' ) {
throw new Error ( 'Expected a script tag with type="text/ohm-js", got ' + el ) ;
}
return el . getAttribute ( 'src' ) ? load ( el . getAttribute ( 'src' ) ) : el . innerHTML ;
}
function grammar ( source , optNamespace ) {
var ns = grammars ( source , optNamespace ) ;
// Ensure that the source contained no more than one grammar definition.
var grammarNames = Object . keys ( ns ) ;
if ( grammarNames . length === 0 ) {
throw new Error ( 'Missing grammar definition' ) ;
} else if ( grammarNames . length > 1 ) {
var secondGrammar = ns [ grammarNames [ 1 ] ] ;
var interval = secondGrammar . definitionInterval ;
throw new Error (
util . getLineAndColumnMessage ( interval . inputStream . source , interval . startIdx ) +
'Found more than one grammar definition -- use ohm.grammars() instead.' ) ;
}
return ns [ grammarNames [ 0 ] ] ; // Return the one and only grammar.
}
function grammars ( source , optNamespace ) {
var ns = Namespace . extend ( Namespace . asNamespace ( optNamespace ) ) ;
if ( typeof source !== 'string' ) {
// For convenience, detect Node.js Buffer objects and automatically call toString().
if ( isBuffer ( source ) ) {
source = source . toString ( ) ;
} else {
throw new TypeError (
'Expected string as first argument, got ' + common . unexpectedObjToString ( source ) ) ;
}
}
compileAndLoad ( source , ns ) ;
return ns ;
}
function grammarFromScriptElement ( optNode ) {
var node = optNode ;
if ( isUndefined ( node ) ) {
var nodeList = documentInterface . querySelectorAll ( 'script[type="text/ohm-js"]' ) ;
if ( nodeList . length !== 1 ) {
throw new Error (
'Expected exactly one script tag with type="text/ohm-js", found ' + nodeList . length ) ;
}
node = nodeList [ 0 ] ;
}
return grammar ( getScriptElementContents ( node ) ) ;
}
function grammarsFromScriptElements ( optNodeOrNodeList ) {
// Simple case: the argument is a DOM node.
if ( isElement ( optNodeOrNodeList ) ) {
return grammars ( optNodeOrNodeList ) ;
}
// Otherwise, it must be either undefined or a NodeList.
var nodeList = optNodeOrNodeList ;
if ( isUndefined ( nodeList ) ) {
// Find all script elements with type="text/ohm-js".
nodeList = documentInterface . querySelectorAll ( 'script[type="text/ohm-js"]' ) ;
} else if ( typeof nodeList === 'string' || ( ! isElement ( nodeList ) && ! isArrayLike ( nodeList ) ) ) {
throw new TypeError ( 'Expected a Node, NodeList, or Array, but got ' + nodeList ) ;
}
var ns = Namespace . createNamespace ( ) ;
for ( var i = 0 ; i < nodeList . length ; ++ i ) {
// Copy the new grammars into `ns` to keep the namespace flat.
common . extend ( ns , grammars ( getScriptElementContents ( nodeList [ i ] ) , ns ) ) ;
}
return ns ;
}
2016-08-07 19:41:10 +00:00
function makeRecipe ( recipeFn ) {
return recipeFn . call ( new Builder ( ) ) ;
2016-04-06 16:22:30 +00:00
}
// --------------------------------------------------------------------
// Exports
// --------------------------------------------------------------------
// Stuff that users should know about
module . exports = {
createNamespace : Namespace . createNamespace ,
grammar : grammar ,
grammars : grammars ,
grammarFromScriptElement : grammarFromScriptElement ,
grammarsFromScriptElements : grammarsFromScriptElements ,
makeRecipe : makeRecipe ,
ohmGrammar : null , // Initialized below, after Grammar.BuiltInRules.
pexprs : pexprs ,
util : util ,
extras : require ( '../extras' )
} ;
// Stuff for testing, etc.
module . exports . _buildGrammar = buildGrammar ;
module . exports . _setDocumentInterfaceForTesting = function ( doc ) { documentInterface = doc ; } ;
// Late initialization for stuff that is bootstrapped.
Grammar . BuiltInRules = require ( '../dist/built-in-rules' ) ;
var Semantics = require ( './Semantics' ) ;
var operationsAndAttributesGrammar = require ( '../dist/operations-and-attributes' ) ;
Semantics . initBuiltInSemantics ( Grammar . BuiltInRules ) ;
Semantics . initPrototypeParser ( operationsAndAttributesGrammar ) ; // requires BuiltInSemantics
module . exports . ohmGrammar = ohmGrammar = require ( '../dist/ohm-grammar' ) ;
2016-05-02 21:15:05 +00:00
Grammar . initApplicationParser ( ohmGrammar , buildGrammar ) ;
2016-04-06 16:22:30 +00:00
2016-05-16 17:27:46 +00:00
} , { "../dist/built-in-rules" : 10 , "../dist/ohm-grammar" : 11 , "../dist/operations-and-attributes" : 12 , "../extras" : 13 , "./Builder" : 36 , "./Grammar" : 38 , "./Namespace" : 43 , "./Semantics" : 45 , "./common" : 48 , "./errors" : 49 , "./pexprs" : 67 , "./util" : 68 , "is-buffer" : 34 } ] , 51 : [ function ( require , module , exports ) {
2016-04-06 16:22:30 +00:00
'use strict' ;
var inherits = require ( 'inherits' ) ;
var common = require ( './common' ) ;
// --------------------------------------------------------------------
// Private stuff
// --------------------------------------------------------------------
function Node ( grammar , ctorName , children , interval ) {
this . grammar = grammar ;
this . ctorName = ctorName ;
this . children = children ;
this . interval = interval ;
}
Node . prototype . numChildren = function ( ) {
return this . children . length ;
} ;
Node . prototype . childAt = function ( idx ) {
return this . children [ idx ] ;
} ;
Node . prototype . indexOfChild = function ( arg ) {
return this . children . indexOf ( arg ) ;
} ;
Node . prototype . hasChildren = function ( ) {
return this . children . length > 0 ;
} ;
Node . prototype . hasNoChildren = function ( ) {
return ! this . hasChildren ( ) ;
} ;
Node . prototype . onlyChild = function ( ) {
if ( this . children . length !== 1 ) {
throw new Error (
'cannot get only child of a node of type ' + this . ctorName +
' (it has ' + this . numChildren ( ) + ' children)' ) ;
} else {
return this . firstChild ( ) ;
}
} ;
Node . prototype . firstChild = function ( ) {
if ( this . hasNoChildren ( ) ) {
throw new Error (
'cannot get first child of a ' + this . ctorName + ' node, which has no children' ) ;
} else {
return this . childAt ( 0 ) ;
}
} ;
Node . prototype . lastChild = function ( ) {
if ( this . hasNoChildren ( ) ) {
throw new Error (
'cannot get last child of a ' + this . ctorName + ' node, which has no children' ) ;
} else {
return this . childAt ( this . numChildren ( ) - 1 ) ;
}
} ;
Node . prototype . childBefore = function ( child ) {
var childIdx = this . indexOfChild ( child ) ;
if ( childIdx < 0 ) {
throw new Error ( 'Node.childBefore() called w/ an argument that is not a child' ) ;
} else if ( childIdx === 0 ) {
throw new Error ( 'cannot get child before first child' ) ;
} else {
return this . childAt ( childIdx - 1 ) ;
}
} ;
Node . prototype . childAfter = function ( child ) {
var childIdx = this . indexOfChild ( child ) ;
if ( childIdx < 0 ) {
throw new Error ( 'Node.childAfter() called w/ an argument that is not a child' ) ;
} else if ( childIdx === this . numChildren ( ) - 1 ) {
throw new Error ( 'cannot get child after last child' ) ;
} else {
return this . childAt ( childIdx + 1 ) ;
}
} ;
Node . prototype . isTerminal = function ( ) {
return false ;
} ;
Node . prototype . isNonterminal = function ( ) {
return false ;
} ;
Node . prototype . isIteration = function ( ) {
return false ;
} ;
Node . prototype . isOptional = function ( ) {
return false ;
} ;
Node . prototype . toJSON = function ( ) {
var r = { } ;
r [ this . ctorName ] = this . children ;
return r ;
} ;
// Terminals
function TerminalNode ( grammar , value , interval ) {
Node . call ( this , grammar , '_terminal' , [ ] , interval ) ;
this . primitiveValue = value ;
}
inherits ( TerminalNode , Node ) ;
TerminalNode . prototype . isTerminal = function ( ) {
return true ;
} ;
// Nonterminals
function NonterminalNode ( grammar , ruleName , children , interval ) {
Node . call ( this , grammar , ruleName , children , interval ) ;
}
inherits ( NonterminalNode , Node ) ;
NonterminalNode . prototype . isNonterminal = function ( ) {
return true ;
} ;
NonterminalNode . prototype . isLexical = function ( ) {
return common . isLexical ( this . ctorName ) ;
} ;
NonterminalNode . prototype . isSyntactic = function ( ) {
return common . isSyntactic ( this . ctorName ) ;
} ;
// Iterations
function IterationNode ( grammar , children , interval , optional ) {
Node . call ( this , grammar , '_iter' , children , interval ) ;
this . optional = optional ;
}
inherits ( IterationNode , Node ) ;
IterationNode . prototype . isIteration = function ( ) {
return true ;
} ;
IterationNode . prototype . isOptional = function ( ) {
return this . optional ;
} ;
// --------------------------------------------------------------------
// Exports
// --------------------------------------------------------------------
module . exports = {
Node : Node ,
TerminalNode : TerminalNode ,
NonterminalNode : NonterminalNode ,
IterationNode : IterationNode
} ;
} , { "./common" : 48 , "inherits" : 33 } ] , 52 : [ function ( require , module , exports ) {
'use strict' ;
// --------------------------------------------------------------------
// Imports
// --------------------------------------------------------------------
2016-05-02 21:15:05 +00:00
var common = require ( './common' ) ;
var pexprs = require ( './pexprs' ) ;
// --------------------------------------------------------------------
// Operations
// --------------------------------------------------------------------
/ *
Return true if we should skip spaces preceding this expression in a syntactic context .
* /
2017-02-20 22:19:56 +00:00
pexprs . PExpr . prototype . allowsSkippingPrecedingSpace = common . abstract ;
2016-05-02 21:15:05 +00:00
/ *
Generally , these are all first - order expressions that operate on strings and ( with the
exception of Apply ) directly read from the input stream .
* /
pexprs . any . allowsSkippingPrecedingSpace =
pexprs . end . allowsSkippingPrecedingSpace =
pexprs . Apply . prototype . allowsSkippingPrecedingSpace =
2016-05-16 17:27:46 +00:00
pexprs . Terminal . prototype . allowsSkippingPrecedingSpace =
2016-05-02 21:15:05 +00:00
pexprs . Range . prototype . allowsSkippingPrecedingSpace =
pexprs . UnicodeChar . prototype . allowsSkippingPrecedingSpace = function ( ) {
return true ;
} ;
/ *
Higher - order expressions that don ' t directly consume input , and expressions that
don ' t operate on string input streams ( e . g . Obj and Arr ) .
* /
pexprs . Alt . prototype . allowsSkippingPrecedingSpace =
pexprs . Iter . prototype . allowsSkippingPrecedingSpace =
pexprs . Lex . prototype . allowsSkippingPrecedingSpace =
pexprs . Lookahead . prototype . allowsSkippingPrecedingSpace =
pexprs . Not . prototype . allowsSkippingPrecedingSpace =
pexprs . Param . prototype . allowsSkippingPrecedingSpace =
2016-05-16 17:27:46 +00:00
pexprs . Seq . prototype . allowsSkippingPrecedingSpace = function ( ) {
2016-05-02 21:15:05 +00:00
return false ;
} ;
2016-05-16 17:27:46 +00:00
} , { "./common" : 48 , "./pexprs" : 67 } ] , 53 : [ function ( require , module , exports ) {
2016-05-02 21:15:05 +00:00
'use strict' ;
// --------------------------------------------------------------------
// Imports
// --------------------------------------------------------------------
2016-04-06 16:22:30 +00:00
var common = require ( './common' ) ;
var errors = require ( './errors' ) ;
var pexprs = require ( './pexprs' ) ;
// --------------------------------------------------------------------
// Operations
// --------------------------------------------------------------------
var lexifyCount ;
pexprs . PExpr . prototype . assertAllApplicationsAreValid = function ( ruleName , grammar ) {
lexifyCount = 0 ;
this . _assertAllApplicationsAreValid ( ruleName , grammar ) ;
} ;
2017-02-20 22:19:56 +00:00
pexprs . PExpr . prototype . _assertAllApplicationsAreValid = common . abstract ;
2016-04-06 16:22:30 +00:00
pexprs . any . _assertAllApplicationsAreValid =
pexprs . end . _assertAllApplicationsAreValid =
2016-05-16 17:27:46 +00:00
pexprs . Terminal . prototype . _assertAllApplicationsAreValid =
2016-04-06 16:22:30 +00:00
pexprs . Range . prototype . _assertAllApplicationsAreValid =
pexprs . Param . prototype . _assertAllApplicationsAreValid =
pexprs . UnicodeChar . prototype . _assertAllApplicationsAreValid = function ( ruleName , grammar ) {
// no-op
} ;
pexprs . Lex . prototype . _assertAllApplicationsAreValid = function ( ruleName , grammar ) {
lexifyCount ++ ;
this . expr . _assertAllApplicationsAreValid ( ruleName , grammar ) ;
lexifyCount -- ;
} ;
pexprs . Alt . prototype . _assertAllApplicationsAreValid = function ( ruleName , grammar ) {
for ( var idx = 0 ; idx < this . terms . length ; idx ++ ) {
this . terms [ idx ] . _assertAllApplicationsAreValid ( ruleName , grammar ) ;
}
} ;
pexprs . Seq . prototype . _assertAllApplicationsAreValid = function ( ruleName , grammar ) {
for ( var idx = 0 ; idx < this . factors . length ; idx ++ ) {
this . factors [ idx ] . _assertAllApplicationsAreValid ( ruleName , grammar ) ;
}
} ;
pexprs . Iter . prototype . _assertAllApplicationsAreValid =
pexprs . Not . prototype . _assertAllApplicationsAreValid =
2016-05-16 17:27:46 +00:00
pexprs . Lookahead . prototype . _assertAllApplicationsAreValid = function ( ruleName , grammar ) {
2016-04-06 16:22:30 +00:00
this . expr . _assertAllApplicationsAreValid ( ruleName , grammar ) ;
} ;
pexprs . Apply . prototype . _assertAllApplicationsAreValid = function ( ruleName , grammar ) {
var body = grammar . ruleBodies [ this . ruleName ] ;
// Make sure that the rule exists...
if ( ! body ) {
throw errors . undeclaredRule ( this . ruleName , grammar . name , this . interval ) ;
}
// ...and that this application is allowed
if ( common . isSyntactic ( this . ruleName ) && ( ! common . isSyntactic ( ruleName ) || lexifyCount > 0 ) ) {
throw errors . applicationOfSyntacticRuleFromLexicalContext ( this . ruleName , this ) ;
}
// ...and that this application has the correct number of arguments
var actual = this . args . length ;
var expected = grammar . ruleFormals [ this . ruleName ] . length ;
if ( actual !== expected ) {
throw errors . wrongNumberOfArguments ( this . ruleName , expected , actual , this ) ;
}
// ...and that all of the argument expressions only have valid applications and have arity 1.
var self = this ;
this . args . forEach ( function ( arg ) {
arg . _assertAllApplicationsAreValid ( ruleName , grammar ) ;
if ( arg . getArity ( ) !== 1 ) {
throw errors . invalidParameter ( self . ruleName , arg ) ;
}
} ) ;
} ;
2016-05-16 17:27:46 +00:00
} , { "./common" : 48 , "./errors" : 49 , "./pexprs" : 67 } ] , 54 : [ function ( require , module , exports ) {
2016-04-06 16:22:30 +00:00
'use strict' ;
// --------------------------------------------------------------------
// Imports
// --------------------------------------------------------------------
var common = require ( './common' ) ;
var errors = require ( './errors' ) ;
var pexprs = require ( './pexprs' ) ;
// --------------------------------------------------------------------
// Operations
// --------------------------------------------------------------------
2017-02-20 22:19:56 +00:00
pexprs . PExpr . prototype . assertChoicesHaveUniformArity = common . abstract ;
2016-04-06 16:22:30 +00:00
pexprs . any . assertChoicesHaveUniformArity =
pexprs . end . assertChoicesHaveUniformArity =
2016-05-16 17:27:46 +00:00
pexprs . Terminal . prototype . assertChoicesHaveUniformArity =
2016-04-06 16:22:30 +00:00
pexprs . Range . prototype . assertChoicesHaveUniformArity =
pexprs . Param . prototype . assertChoicesHaveUniformArity =
pexprs . Lex . prototype . assertChoicesHaveUniformArity =
pexprs . UnicodeChar . prototype . assertChoicesHaveUniformArity = function ( ruleName ) {
// no-op
} ;
pexprs . Alt . prototype . assertChoicesHaveUniformArity = function ( ruleName ) {
if ( this . terms . length === 0 ) {
return ;
}
var arity = this . terms [ 0 ] . getArity ( ) ;
for ( var idx = 0 ; idx < this . terms . length ; idx ++ ) {
var term = this . terms [ idx ] ;
term . assertChoicesHaveUniformArity ( ) ;
var otherArity = term . getArity ( ) ;
if ( arity !== otherArity ) {
throw errors . inconsistentArity ( ruleName , arity , otherArity , term ) ;
}
}
} ;
pexprs . Extend . prototype . assertChoicesHaveUniformArity = function ( ruleName ) {
// Extend is a special case of Alt that's guaranteed to have exactly two
// cases: [extensions, origBody].
var actualArity = this . terms [ 0 ] . getArity ( ) ;
var expectedArity = this . terms [ 1 ] . getArity ( ) ;
if ( actualArity !== expectedArity ) {
throw errors . inconsistentArity ( ruleName , expectedArity , actualArity , this . terms [ 0 ] ) ;
}
} ;
pexprs . Seq . prototype . assertChoicesHaveUniformArity = function ( ruleName ) {
for ( var idx = 0 ; idx < this . factors . length ; idx ++ ) {
this . factors [ idx ] . assertChoicesHaveUniformArity ( ruleName ) ;
}
} ;
pexprs . Iter . prototype . assertChoicesHaveUniformArity = function ( ruleName ) {
this . expr . assertChoicesHaveUniformArity ( ruleName ) ;
} ;
pexprs . Not . prototype . assertChoicesHaveUniformArity = function ( ruleName ) {
// no-op (not required b/c the nested expr doesn't show up in the CST)
} ;
2016-05-16 17:27:46 +00:00
pexprs . Lookahead . prototype . assertChoicesHaveUniformArity = function ( ruleName ) {
2016-04-06 16:22:30 +00:00
this . expr . assertChoicesHaveUniformArity ( ruleName ) ;
} ;
pexprs . Apply . prototype . assertChoicesHaveUniformArity = function ( ruleName ) {
// The arities of the parameter expressions is required to be 1 by
// `assertAllApplicationsAreValid()`.
} ;
2016-05-16 17:27:46 +00:00
} , { "./common" : 48 , "./errors" : 49 , "./pexprs" : 67 } ] , 55 : [ function ( require , module , exports ) {
2016-04-06 16:22:30 +00:00
'use strict' ;
// --------------------------------------------------------------------
// Imports
// --------------------------------------------------------------------
var common = require ( './common' ) ;
var errors = require ( './errors' ) ;
var pexprs = require ( './pexprs' ) ;
// --------------------------------------------------------------------
// Operations
// --------------------------------------------------------------------
2017-02-20 22:19:56 +00:00
pexprs . PExpr . prototype . assertIteratedExprsAreNotNullable = common . abstract ;
2016-04-06 16:22:30 +00:00
pexprs . any . assertIteratedExprsAreNotNullable =
pexprs . end . assertIteratedExprsAreNotNullable =
2016-05-16 17:27:46 +00:00
pexprs . Terminal . prototype . assertIteratedExprsAreNotNullable =
2016-04-06 16:22:30 +00:00
pexprs . Range . prototype . assertIteratedExprsAreNotNullable =
pexprs . Param . prototype . assertIteratedExprsAreNotNullable =
pexprs . UnicodeChar . prototype . assertIteratedExprsAreNotNullable = function ( grammar , ruleName ) {
// no-op
} ;
pexprs . Alt . prototype . assertIteratedExprsAreNotNullable = function ( grammar , ruleName ) {
for ( var idx = 0 ; idx < this . terms . length ; idx ++ ) {
this . terms [ idx ] . assertIteratedExprsAreNotNullable ( grammar , ruleName ) ;
}
} ;
pexprs . Seq . prototype . assertIteratedExprsAreNotNullable = function ( grammar , ruleName ) {
for ( var idx = 0 ; idx < this . factors . length ; idx ++ ) {
this . factors [ idx ] . assertIteratedExprsAreNotNullable ( grammar , ruleName ) ;
}
} ;
pexprs . Iter . prototype . assertIteratedExprsAreNotNullable = function ( grammar , ruleName ) {
// Note: this is the implementation of this method for `Star` and `Plus` expressions.
// It is overridden for `Opt` below.
this . expr . assertIteratedExprsAreNotNullable ( grammar , ruleName ) ;
if ( this . expr . isNullable ( grammar ) ) {
throw errors . kleeneExprHasNullableOperand ( this , ruleName ) ;
}
} ;
pexprs . Opt . prototype . assertIteratedExprsAreNotNullable =
pexprs . Not . prototype . assertIteratedExprsAreNotNullable =
pexprs . Lookahead . prototype . assertIteratedExprsAreNotNullable =
2016-05-16 17:27:46 +00:00
pexprs . Lex . prototype . assertIteratedExprsAreNotNullable = function ( grammar , ruleName ) {
2016-04-06 16:22:30 +00:00
this . expr . assertIteratedExprsAreNotNullable ( grammar , ruleName ) ;
} ;
pexprs . Apply . prototype . assertIteratedExprsAreNotNullable = function ( grammar , ruleName ) {
this . args . forEach ( function ( arg ) {
arg . assertIteratedExprsAreNotNullable ( grammar , ruleName ) ;
} ) ;
} ;
2016-05-16 17:27:46 +00:00
} , { "./common" : 48 , "./errors" : 49 , "./pexprs" : 67 } ] , 56 : [ function ( require , module , exports ) {
2016-04-06 16:22:30 +00:00
'use strict' ;
// --------------------------------------------------------------------
// Imports
// --------------------------------------------------------------------
var common = require ( './common' ) ;
var nodes = require ( './nodes' ) ;
var pexprs = require ( './pexprs' ) ;
// --------------------------------------------------------------------
// Operations
// --------------------------------------------------------------------
2017-02-20 22:19:56 +00:00
pexprs . PExpr . prototype . check = common . abstract ;
2016-04-06 16:22:30 +00:00
pexprs . any . check = function ( grammar , vals ) {
return vals . length >= 1 ;
} ;
pexprs . end . check = function ( grammar , vals ) {
return vals [ 0 ] instanceof nodes . Node &&
vals [ 0 ] . isTerminal ( ) &&
vals [ 0 ] . primitiveValue === undefined ;
} ;
2016-05-16 17:27:46 +00:00
pexprs . Terminal . prototype . check = function ( grammar , vals ) {
2016-04-06 16:22:30 +00:00
return vals [ 0 ] instanceof nodes . Node &&
vals [ 0 ] . isTerminal ( ) &&
vals [ 0 ] . primitiveValue === this . obj ;
} ;
pexprs . Range . prototype . check = function ( grammar , vals ) {
return vals [ 0 ] instanceof nodes . Node &&
vals [ 0 ] . isTerminal ( ) &&
typeof vals [ 0 ] . primitiveValue === typeof this . from ;
} ;
pexprs . Param . prototype . check = function ( grammar , vals ) {
return vals . length >= 1 ;
} ;
pexprs . Alt . prototype . check = function ( grammar , vals ) {
for ( var i = 0 ; i < this . terms . length ; i ++ ) {
var term = this . terms [ i ] ;
if ( term . check ( grammar , vals ) ) {
return true ;
}
}
return false ;
} ;
pexprs . Seq . prototype . check = function ( grammar , vals ) {
var pos = 0 ;
for ( var i = 0 ; i < this . factors . length ; i ++ ) {
var factor = this . factors [ i ] ;
if ( factor . check ( grammar , vals . slice ( pos ) ) ) {
pos += factor . getArity ( ) ;
} else {
return false ;
}
}
return true ;
} ;
pexprs . Iter . prototype . check = function ( grammar , vals ) {
var arity = this . getArity ( ) ;
var columns = vals . slice ( 0 , arity ) ;
if ( columns . length !== arity ) {
return false ;
}
var rowCount = columns [ 0 ] . length ;
var i ;
for ( i = 1 ; i < arity ; i ++ ) {
if ( columns [ i ] . length !== rowCount ) {
return false ;
}
}
for ( i = 0 ; i < rowCount ; i ++ ) {
var row = [ ] ;
for ( var j = 0 ; j < arity ; j ++ ) {
row . push ( columns [ j ] [ i ] ) ;
}
if ( ! this . expr . check ( grammar , row ) ) {
return false ;
}
}
return true ;
} ;
pexprs . Not . prototype . check = function ( grammar , vals ) {
return true ;
} ;
pexprs . Lookahead . prototype . check =
2016-05-16 17:27:46 +00:00
pexprs . Lex . prototype . check = function ( grammar , vals ) {
2016-04-06 16:22:30 +00:00
return this . expr . check ( grammar , vals ) ;
} ;
pexprs . Apply . prototype . check = function ( grammar , vals ) {
if ( ! ( vals [ 0 ] instanceof nodes . Node &&
vals [ 0 ] . grammar === grammar &&
vals [ 0 ] . ctorName === this . ruleName ) ) {
return false ;
}
// TODO: think about *not* doing the following checks, i.e., trusting that the rule
// was correctly constructed.
var ruleNode = vals [ 0 ] ;
var body = grammar . ruleBodies [ this . ruleName ] ;
return body . check ( grammar , ruleNode . children ) && ruleNode . numChildren ( ) === body . getArity ( ) ;
} ;
pexprs . UnicodeChar . prototype . check = function ( grammar , vals ) {
return vals [ 0 ] instanceof nodes . Node &&
vals [ 0 ] . isTerminal ( ) &&
typeof vals [ 0 ] . primitiveValue === 'string' ;
} ;
2016-05-16 17:27:46 +00:00
} , { "./common" : 48 , "./nodes" : 51 , "./pexprs" : 67 } ] , 57 : [ function ( require , module , exports ) {
2016-04-06 16:22:30 +00:00
'use strict' ;
// --------------------------------------------------------------------
// Imports
// --------------------------------------------------------------------
var Trace = require ( './Trace' ) ;
var common = require ( './common' ) ;
var nodes = require ( './nodes' ) ;
var pexprs = require ( './pexprs' ) ;
var TerminalNode = nodes . TerminalNode ;
var NonterminalNode = nodes . NonterminalNode ;
var IterationNode = nodes . IterationNode ;
// --------------------------------------------------------------------
// Operations
// --------------------------------------------------------------------
/ *
Evaluate the expression and return ` true ` if it succeeds , ` false ` otherwise . This method should
only be called directly by ` State.prototype.eval(expr) ` , which also updates the data structures
that are used for tracing . ( Making those updates in a method of ` State ` enables the trace - specific
data structures to be "secrets" of that class , which is good for modularity . )
The contract of this method is as follows :
* When the return value is ` true ` ,
- the state object will have ` expr.getArity() ` more bindings than it did before the call .
* When the return value is ` false ` ,
- the state object may have more bindings than it did before the call , and
- its input stream ' s position may be anywhere .
Note that ` State.prototype.eval(expr) ` , unlike this method , guarantees that neither the state
object 's bindings nor its input stream' s position will change if the expression fails to match .
* /
2017-02-20 22:19:56 +00:00
pexprs . PExpr . prototype . eval = common . abstract ; // function(state) { ... }
2016-04-06 16:22:30 +00:00
pexprs . any . eval = function ( state ) {
var inputStream = state . inputStream ;
2016-05-02 21:15:05 +00:00
var origPos = inputStream . pos ;
2016-05-16 17:27:46 +00:00
var ch = inputStream . next ( ) ;
if ( ch ) {
2016-05-15 20:20:50 +00:00
var interval = inputStream . interval ( origPos ) ;
2016-05-16 17:27:46 +00:00
state . bindings . push ( new TerminalNode ( state . grammar , ch , interval ) ) ;
2016-05-15 20:20:50 +00:00
return true ;
2016-05-16 17:27:46 +00:00
} else {
state . processFailure ( origPos , this ) ;
return false ;
2016-04-06 16:22:30 +00:00
}
} ;
pexprs . end . eval = function ( state ) {
var inputStream = state . inputStream ;
2016-05-02 21:15:05 +00:00
var origPos = inputStream . pos ;
2016-04-06 16:22:30 +00:00
if ( inputStream . atEnd ( ) ) {
var interval = inputStream . interval ( inputStream . pos ) ;
state . bindings . push ( new TerminalNode ( state . grammar , undefined , interval ) ) ;
return true ;
} else {
state . processFailure ( origPos , this ) ;
return false ;
}
} ;
2016-05-16 17:27:46 +00:00
pexprs . Terminal . prototype . eval = function ( state ) {
2016-04-06 16:22:30 +00:00
var inputStream = state . inputStream ;
2016-05-02 21:15:05 +00:00
var origPos = inputStream . pos ;
2016-05-16 17:27:46 +00:00
if ( ! inputStream . matchString ( this . obj ) ) {
2016-04-06 16:22:30 +00:00
state . processFailure ( origPos , this ) ;
return false ;
} else {
var interval = inputStream . interval ( origPos ) ;
var primitiveValue = this . obj ;
state . bindings . push ( new TerminalNode ( state . grammar , primitiveValue , interval ) ) ;
return true ;
}
} ;
pexprs . Range . prototype . eval = function ( state ) {
var inputStream = state . inputStream ;
2016-05-02 21:15:05 +00:00
var origPos = inputStream . pos ;
2016-05-16 17:27:46 +00:00
var ch = inputStream . next ( ) ;
if ( ch && this . from <= ch && ch <= this . to ) {
2016-04-06 16:22:30 +00:00
var interval = inputStream . interval ( origPos ) ;
2016-05-16 17:27:46 +00:00
state . bindings . push ( new TerminalNode ( state . grammar , ch , interval ) ) ;
2016-04-06 16:22:30 +00:00
return true ;
} else {
state . processFailure ( origPos , this ) ;
return false ;
}
} ;
pexprs . Param . prototype . eval = function ( state ) {
return state . eval ( state . currentApplication ( ) . args [ this . index ] ) ;
} ;
pexprs . Lex . prototype . eval = function ( state ) {
state . enterLexifiedContext ( ) ;
var ans = state . eval ( this . expr ) ;
state . exitLexifiedContext ( ) ;
return ans ;
} ;
pexprs . Alt . prototype . eval = function ( state ) {
for ( var idx = 0 ; idx < this . terms . length ; idx ++ ) {
if ( state . eval ( this . terms [ idx ] ) ) {
return true ;
}
}
return false ;
} ;
pexprs . Seq . prototype . eval = function ( state ) {
for ( var idx = 0 ; idx < this . factors . length ; idx ++ ) {
var factor = this . factors [ idx ] ;
if ( ! state . eval ( factor ) ) {
return false ;
}
}
return true ;
} ;
pexprs . Iter . prototype . eval = function ( state ) {
var inputStream = state . inputStream ;
var origPos = inputStream . pos ;
var arity = this . getArity ( ) ;
var cols = [ ] ;
while ( cols . length < arity ) {
cols . push ( [ ] ) ;
}
var numMatches = 0 ;
var idx ;
while ( numMatches < this . maxNumMatches && state . eval ( this . expr ) ) {
numMatches ++ ;
var row = state . bindings . splice ( state . bindings . length - arity , arity ) ;
for ( idx = 0 ; idx < row . length ; idx ++ ) {
cols [ idx ] . push ( row [ idx ] ) ;
}
}
if ( numMatches < this . minNumMatches ) {
return false ;
}
var interval ;
if ( numMatches === 0 ) {
interval = inputStream . interval ( origPos , origPos ) ;
} else {
var firstCol = cols [ 0 ] ;
var lastCol = cols [ cols . length - 1 ] ;
interval = inputStream . interval (
firstCol [ 0 ] . interval . startIdx ,
lastCol [ lastCol . length - 1 ] . interval . endIdx ) ;
}
for ( idx = 0 ; idx < cols . length ; idx ++ ) {
state . bindings . push ( new IterationNode ( state . grammar , cols [ idx ] , interval ,
this instanceof pexprs . Opt ) ) ;
}
return true ;
} ;
pexprs . Not . prototype . eval = function ( state ) {
/ *
TODO :
- Right now we ' re just throwing away all of the failures that happen inside a ` not ` , and
recording ` this ` as a failed expression .
- Double negation should be equivalent to lookahead , but that ' s not the case right now wrt
failures . E . g . , ~ ~ 'foo' produces a failure for ~ ~ 'foo' , but maybe it should produce
a failure for 'foo' instead .
* /
var inputStream = state . inputStream ;
var origPos = inputStream . pos ;
var failuresInfo = state . getFailuresInfo ( ) ;
var ans = state . eval ( this . expr ) ;
state . restoreFailuresInfo ( failuresInfo ) ;
if ( ans ) {
state . processFailure ( origPos , this ) ;
return false ;
}
inputStream . pos = origPos ;
return true ;
} ;
pexprs . Lookahead . prototype . eval = function ( state ) {
var inputStream = state . inputStream ;
var origPos = inputStream . pos ;
if ( state . eval ( this . expr ) ) {
inputStream . pos = origPos ;
return true ;
} else {
return false ;
}
} ;
pexprs . Apply . prototype . eval = function ( state ) {
var caller = state . currentApplication ( ) ;
var actuals = caller ? caller . args : [ ] ;
var app = this . substituteParams ( actuals ) ;
var posInfo = state . getCurrentPosInfo ( ) ;
if ( posInfo . isActive ( app ) ) {
// This rule is already active at this position, i.e., it is left-recursive.
return app . handleCycle ( state ) ;
}
var memoKey = app . toMemoKey ( ) ;
var memoRec = posInfo . memo [ memoKey ] ;
return memoRec && posInfo . shouldUseMemoizedResult ( memoRec ) ?
state . useMemoizedResult ( memoRec ) :
2016-05-02 21:15:05 +00:00
app . reallyEval ( state ) ;
2016-04-06 16:22:30 +00:00
} ;
pexprs . Apply . prototype . handleCycle = function ( state ) {
var posInfo = state . getCurrentPosInfo ( ) ;
var currentLeftRecursion = posInfo . currentLeftRecursion ;
var memoKey = this . toMemoKey ( ) ;
var memoRec = posInfo . memo [ memoKey ] ;
if ( currentLeftRecursion && currentLeftRecursion . headApplication . toMemoKey ( ) === memoKey ) {
// We already know about this left recursion, but it's possible there are "involved
// applications" that we don't already know about, so...
memoRec . updateInvolvedApplicationMemoKeys ( ) ;
} else if ( ! memoRec ) {
// New left recursion detected! Memoize a failure to try to get a seed parse.
2016-05-02 21:15:05 +00:00
memoRec = posInfo . memo [ memoKey ] = { pos : - 1 , value : false } ;
2016-04-06 16:22:30 +00:00
posInfo . startLeftRecursion ( this , memoRec ) ;
}
return state . useMemoizedResult ( memoRec ) ;
} ;
2016-05-02 21:15:05 +00:00
pexprs . Apply . prototype . reallyEval = function ( state ) {
2016-04-06 16:22:30 +00:00
var inputStream = state . inputStream ;
var origPos = inputStream . pos ;
var origPosInfo = state . getCurrentPosInfo ( ) ;
var body = state . grammar . ruleBodies [ this . ruleName ] ;
var description = state . grammar . ruleDescriptions [ this . ruleName ] ;
origPosInfo . enter ( this ) ;
if ( description ) {
var origFailuresInfo = state . getFailuresInfo ( ) ;
}
var value = this . evalOnce ( body , state ) ;
var currentLR = origPosInfo . currentLeftRecursion ;
var memoKey = this . toMemoKey ( ) ;
2016-08-07 19:41:10 +00:00
var isHeadOfLeftRecursion = currentLR && currentLR . headApplication . toMemoKey ( ) === memoKey ;
2016-04-06 16:22:30 +00:00
var memoized = true ;
if ( isHeadOfLeftRecursion ) {
value = this . growSeedResult ( body , state , origPos , currentLR , value ) ;
origPosInfo . endLeftRecursion ( ) ;
} else if ( currentLR && currentLR . isInvolved ( memoKey ) ) {
// Don't memoize the result
memoized = false ;
} else {
origPosInfo . memo [ memoKey ] = {
pos : inputStream . pos ,
value : value ,
failuresAtRightmostPosition : state . cloneRightmostFailures ( )
} ;
}
if ( description ) {
state . restoreFailuresInfo ( origFailuresInfo ) ;
if ( ! value ) {
state . processFailure ( origPos , this ) ;
}
if ( memoized ) {
origPosInfo . memo [ memoKey ] . failuresAtRightmostPosition = state . cloneRightmostFailures ( ) ;
}
}
// Record trace information in the memo table, so that it is available if the memoized result
// is used later.
if ( state . isTracing ( ) && origPosInfo . memo [ memoKey ] ) {
2016-05-02 21:15:05 +00:00
var succeeded = ! ! value ;
var entry = state . getTraceEntry ( origPos , this , succeeded , succeeded ? [ value ] : [ ] ) ;
2016-08-07 19:41:10 +00:00
entry . isLeftRecursive = isHeadOfLeftRecursion ;
2016-04-06 16:22:30 +00:00
origPosInfo . memo [ memoKey ] . traceEntry = entry ;
}
origPosInfo . exit ( ) ;
if ( value ) {
state . bindings . push ( value ) ;
2016-05-02 21:15:05 +00:00
return true ;
2016-04-06 16:22:30 +00:00
} else {
return false ;
}
} ;
pexprs . Apply . prototype . evalOnce = function ( expr , state ) {
var inputStream = state . inputStream ;
var origPos = inputStream . pos ;
if ( state . eval ( expr ) ) {
var arity = expr . getArity ( ) ;
var bindings = state . bindings . splice ( state . bindings . length - arity , arity ) ;
var ans =
new NonterminalNode ( state . grammar , this . ruleName , bindings , inputStream . interval ( origPos ) ) ;
return ans ;
} else {
return false ;
}
} ;
pexprs . Apply . prototype . growSeedResult = function ( body , state , origPos , lrMemoRec , newValue ) {
if ( ! newValue ) {
return false ;
}
var inputStream = state . inputStream ;
while ( true ) {
lrMemoRec . pos = inputStream . pos ;
lrMemoRec . value = newValue ;
lrMemoRec . failuresAtRightmostPosition = state . cloneRightmostFailures ( ) ;
if ( state . isTracing ( ) ) {
2016-05-02 21:15:05 +00:00
// Before evaluating the body again, add a trace node for this application to the memo entry.
2016-08-07 19:41:10 +00:00
// Its only child is the trace node from `newValue`, which will always be the last element
// in `state.trace`.
var children = state . trace . slice ( - 1 ) ;
2016-05-02 21:15:05 +00:00
lrMemoRec . traceEntry = new Trace (
2016-08-07 19:41:10 +00:00
state . inputStream , origPos , this , true , [ newValue ] , children ) ;
2016-04-06 16:22:30 +00:00
}
inputStream . pos = origPos ;
newValue = this . evalOnce ( body , state ) ;
if ( inputStream . pos <= lrMemoRec . pos ) {
break ;
}
}
if ( state . isTracing ( ) ) {
2016-08-07 19:41:10 +00:00
state . trace . pop ( ) ; // Drop last trace entry since `value` was unused.
lrMemoRec . traceEntry = null ;
2016-04-06 16:22:30 +00:00
}
inputStream . pos = lrMemoRec . pos ;
return lrMemoRec . value ;
} ;
pexprs . UnicodeChar . prototype . eval = function ( state ) {
var inputStream = state . inputStream ;
2016-05-02 21:15:05 +00:00
var origPos = inputStream . pos ;
2016-05-16 17:27:46 +00:00
var ch = inputStream . next ( ) ;
if ( ch && this . pattern . test ( ch ) ) {
2016-05-15 20:20:50 +00:00
var interval = inputStream . interval ( origPos ) ;
2016-05-16 17:27:46 +00:00
state . bindings . push ( new TerminalNode ( state . grammar , ch , interval ) ) ;
2016-05-15 20:20:50 +00:00
return true ;
2016-05-16 17:27:46 +00:00
} else {
state . processFailure ( origPos , this ) ;
return false ;
2016-04-06 16:22:30 +00:00
}
} ;
2016-05-16 17:27:46 +00:00
} , { "./Trace" : 47 , "./common" : 48 , "./nodes" : 51 , "./pexprs" : 67 } ] , 58 : [ function ( require , module , exports ) {
2016-04-06 16:22:30 +00:00
'use strict' ;
// --------------------------------------------------------------------
// Imports
// --------------------------------------------------------------------
var common = require ( './common' ) ;
var pexprs = require ( './pexprs' ) ;
// --------------------------------------------------------------------
// Operations
// --------------------------------------------------------------------
2017-02-20 22:19:56 +00:00
pexprs . PExpr . prototype . getArity = common . abstract ;
2016-04-06 16:22:30 +00:00
pexprs . any . getArity =
pexprs . end . getArity =
2016-05-16 17:27:46 +00:00
pexprs . Terminal . prototype . getArity =
2016-04-06 16:22:30 +00:00
pexprs . Range . prototype . getArity =
pexprs . Param . prototype . getArity =
pexprs . Apply . prototype . getArity =
pexprs . UnicodeChar . prototype . getArity = function ( ) {
return 1 ;
} ;
pexprs . Alt . prototype . getArity = function ( ) {
// This is ok b/c all terms must have the same arity -- this property is
// checked by the Grammar constructor.
return this . terms . length === 0 ? 0 : this . terms [ 0 ] . getArity ( ) ;
} ;
pexprs . Seq . prototype . getArity = function ( ) {
var arity = 0 ;
for ( var idx = 0 ; idx < this . factors . length ; idx ++ ) {
arity += this . factors [ idx ] . getArity ( ) ;
}
return arity ;
} ;
pexprs . Iter . prototype . getArity = function ( ) {
return this . expr . getArity ( ) ;
} ;
pexprs . Not . prototype . getArity = function ( ) {
return 0 ;
} ;
pexprs . Lookahead . prototype . getArity =
2016-05-16 17:27:46 +00:00
pexprs . Lex . prototype . getArity = function ( ) {
2016-04-06 16:22:30 +00:00
return this . expr . getArity ( ) ;
} ;
2016-05-16 17:27:46 +00:00
} , { "./common" : 48 , "./pexprs" : 67 } ] , 59 : [ function ( require , module , exports ) {
2016-04-06 16:22:30 +00:00
'use strict' ;
// --------------------------------------------------------------------
// Imports
// --------------------------------------------------------------------
var common = require ( './common' ) ;
var pexprs = require ( './pexprs' ) ;
// --------------------------------------------------------------------
// Operations
// --------------------------------------------------------------------
/ *
Called at grammar creation time to rewrite a rule body , replacing each reference to a formal
parameter with a ` Param ` node . Returns a PExpr -- either a new one , or the original one if
it was modified in place .
* /
2017-02-20 22:19:56 +00:00
pexprs . PExpr . prototype . introduceParams = common . abstract ;
2016-04-06 16:22:30 +00:00
pexprs . any . introduceParams =
pexprs . end . introduceParams =
2016-05-16 17:27:46 +00:00
pexprs . Terminal . prototype . introduceParams =
2016-04-06 16:22:30 +00:00
pexprs . Range . prototype . introduceParams =
pexprs . Param . prototype . introduceParams =
pexprs . UnicodeChar . prototype . introduceParams = function ( formals ) {
return this ;
} ;
pexprs . Alt . prototype . introduceParams = function ( formals ) {
this . terms . forEach ( function ( term , idx , terms ) {
terms [ idx ] = term . introduceParams ( formals ) ;
} ) ;
return this ;
} ;
pexprs . Seq . prototype . introduceParams = function ( formals ) {
this . factors . forEach ( function ( factor , idx , factors ) {
factors [ idx ] = factor . introduceParams ( formals ) ;
} ) ;
return this ;
} ;
pexprs . Iter . prototype . introduceParams =
pexprs . Not . prototype . introduceParams =
pexprs . Lookahead . prototype . introduceParams =
2016-05-16 17:27:46 +00:00
pexprs . Lex . prototype . introduceParams = function ( formals ) {
2016-04-06 16:22:30 +00:00
this . expr = this . expr . introduceParams ( formals ) ;
return this ;
} ;
pexprs . Apply . prototype . introduceParams = function ( formals ) {
var index = formals . indexOf ( this . ruleName ) ;
if ( index >= 0 ) {
if ( this . args . length > 0 ) {
// TODO: Should this be supported? See issue #64.
throw new Error ( 'Parameterized rules cannot be passed as arguments to another rule.' ) ;
}
return new pexprs . Param ( index ) ;
} else {
this . args . forEach ( function ( arg , idx , args ) {
args [ idx ] = arg . introduceParams ( formals ) ;
} ) ;
return this ;
}
} ;
2016-05-16 17:27:46 +00:00
} , { "./common" : 48 , "./pexprs" : 67 } ] , 60 : [ function ( require , module , exports ) {
2016-04-06 16:22:30 +00:00
'use strict' ;
// --------------------------------------------------------------------
// Imports
// --------------------------------------------------------------------
var common = require ( './common' ) ;
var pexprs = require ( './pexprs' ) ;
// --------------------------------------------------------------------
// Operations
// --------------------------------------------------------------------
// Returns `true` if this parsing expression may accept without consuming any input.
pexprs . PExpr . prototype . isNullable = function ( grammar ) {
return this . _isNullable ( grammar , Object . create ( null ) ) ;
} ;
2017-02-20 22:19:56 +00:00
pexprs . PExpr . prototype . _isNullable = common . abstract ;
2016-04-06 16:22:30 +00:00
pexprs . any . _isNullable =
pexprs . Range . prototype . _isNullable =
pexprs . Param . prototype . _isNullable =
pexprs . Plus . prototype . _isNullable =
pexprs . UnicodeChar . prototype . _isNullable = function ( grammar , memo ) {
return false ;
} ;
pexprs . end . _isNullable = function ( grammar , memo ) {
return true ;
} ;
2016-05-16 17:27:46 +00:00
pexprs . Terminal . prototype . _isNullable = function ( grammar , memo ) {
2016-04-06 16:22:30 +00:00
if ( typeof this . obj === 'string' ) {
// This is an over-simplification: it's only correct if the input is a string. If it's an array
// or an object, then the empty string parsing expression is not nullable.
return this . obj === '' ;
} else {
return false ;
}
} ;
pexprs . Alt . prototype . _isNullable = function ( grammar , memo ) {
return this . terms . length === 0 ||
this . terms . some ( function ( term ) { return term . _isNullable ( grammar , memo ) ; } ) ;
} ;
pexprs . Seq . prototype . _isNullable = function ( grammar , memo ) {
return this . factors . every ( function ( factor ) { return factor . _isNullable ( grammar , memo ) ; } ) ;
} ;
pexprs . Star . prototype . _isNullable =
pexprs . Opt . prototype . _isNullable =
pexprs . Not . prototype . _isNullable =
pexprs . Lookahead . prototype . _isNullable = function ( grammar , memo ) {
return true ;
} ;
pexprs . Lex . prototype . _isNullable = function ( grammar , memo ) {
return this . expr . _isNullable ( grammar , memo ) ;
} ;
pexprs . Apply . prototype . _isNullable = function ( grammar , memo ) {
var key = this . toMemoKey ( ) ;
if ( ! Object . prototype . hasOwnProperty . call ( memo , key ) ) {
var body = grammar . ruleBodies [ this . ruleName ] ;
var inlined = body . substituteParams ( this . args ) ;
memo [ key ] = false ; // Prevent infinite recursion for recursive rules.
memo [ key ] = inlined . _isNullable ( grammar , memo ) ;
}
return memo [ key ] ;
} ;
2016-05-16 17:27:46 +00:00
} , { "./common" : 48 , "./pexprs" : 67 } ] , 61 : [ function ( require , module , exports ) {
2016-04-06 16:22:30 +00:00
'use strict' ;
// --------------------------------------------------------------------
// Imports
// --------------------------------------------------------------------
var common = require ( './common' ) ;
var pexprs = require ( './pexprs' ) ;
// --------------------------------------------------------------------
// Private stuff
// --------------------------------------------------------------------
2016-08-07 19:41:10 +00:00
function escapeString ( str ) {
var output = JSON . stringify ( str ) ;
output = output . replace ( /[\u2028\u2029]/g , function ( char , pos , str ) {
var hex = char . codePointAt ( 0 ) . toString ( 16 ) ;
return '\\u' + '0000' . slice ( hex . length ) + hex ;
} ) ;
return output ;
}
function getIntervalInfo ( expr , grammarInterval ) {
2016-04-06 16:22:30 +00:00
if ( expr . interval && grammarInterval ) {
var adjusted = expr . interval . relativeTo ( grammarInterval ) ;
2016-08-07 19:41:10 +00:00
var start = adjusted . startIdx ;
var end = adjusted . endIdx ;
return '.withInterval(decl.sourceInterval(' + start + ', ' + end + '))' ;
2016-04-06 16:22:30 +00:00
}
2016-08-07 19:41:10 +00:00
return '' ;
2016-04-06 16:22:30 +00:00
}
// --------------------------------------------------------------------
// Operations
// --------------------------------------------------------------------
2017-02-20 22:19:56 +00:00
pexprs . PExpr . prototype . outputRecipe = common . abstract ;
2016-04-06 16:22:30 +00:00
2016-08-07 19:41:10 +00:00
pexprs . any . outputRecipe = function ( sb , formals , grammarInterval ) {
throw new Error ( 'should never output a recipe for `any` expression' ) ;
2016-04-06 16:22:30 +00:00
} ;
2016-08-07 19:41:10 +00:00
pexprs . end . outputRecipe = function ( sb , formals , grammarInterval ) {
throw new Error ( 'should never output a recipe for `end` expression' ) ;
2016-04-06 16:22:30 +00:00
} ;
2016-08-07 19:41:10 +00:00
pexprs . Terminal . prototype . outputRecipe = function ( sb , formals , grammarInterval ) {
sb . append ( 'this.terminal(' ) ;
sb . append ( typeof this . obj === 'string' ? escapeString ( this . obj ) : '' + this . obj ) ;
sb . append ( ')' + getIntervalInfo ( this , grammarInterval ) ) ;
2016-04-06 16:22:30 +00:00
} ;
2016-08-07 19:41:10 +00:00
pexprs . Range . prototype . outputRecipe = function ( sb , formals , grammarInterval ) {
sb . append ( 'this.range(' ) ;
sb . append ( JSON . stringify ( this . from ) ) ;
sb . append ( ', ' ) ;
sb . append ( JSON . stringify ( this . to ) ) ;
sb . append ( ')' + getIntervalInfo ( this , grammarInterval ) ) ;
2016-04-06 16:22:30 +00:00
} ;
2016-08-07 19:41:10 +00:00
pexprs . Param . prototype . outputRecipe = function ( sb , formals , grammarInterval ) {
sb . append ( 'this.param(' + this . index + ')' + getIntervalInfo ( this , grammarInterval ) ) ;
2016-04-06 16:22:30 +00:00
} ;
2016-08-07 19:41:10 +00:00
pexprs . Alt . prototype . outputRecipe = function ( sb , formals , grammarInterval ) {
sb . append ( 'this.alt(' ) ;
for ( var idx = 0 ; idx < this . terms . length ; idx ++ ) {
if ( idx > 0 ) {
sb . append ( ', ' ) ;
}
this . terms [ idx ] . outputRecipe ( sb , formals , grammarInterval ) ;
}
sb . append ( ')' + getIntervalInfo ( this , grammarInterval ) ) ;
2016-04-06 16:22:30 +00:00
} ;
2016-08-07 19:41:10 +00:00
pexprs . Extend . prototype . outputRecipe = function ( sb , formals , grammarInterval ) {
2016-04-06 16:22:30 +00:00
var extension = this . terms [ 0 ] ; // [extension, orginal]
2016-08-07 19:41:10 +00:00
extension . outputRecipe ( sb , formals , grammarInterval ) ;
2016-04-06 16:22:30 +00:00
} ;
2016-08-07 19:41:10 +00:00
pexprs . Seq . prototype . outputRecipe = function ( sb , formals , grammarInterval ) {
sb . append ( 'this.seq(' ) ;
for ( var idx = 0 ; idx < this . factors . length ; idx ++ ) {
if ( idx > 0 ) {
sb . append ( ', ' ) ;
}
this . factors [ idx ] . outputRecipe ( sb , formals , grammarInterval ) ;
}
sb . append ( ')' + getIntervalInfo ( this , grammarInterval ) ) ;
2016-04-06 16:22:30 +00:00
} ;
pexprs . Star . prototype . outputRecipe =
pexprs . Plus . prototype . outputRecipe =
pexprs . Opt . prototype . outputRecipe =
pexprs . Not . prototype . outputRecipe =
2016-08-07 19:41:10 +00:00
pexprs . Lex . prototype . outputRecipe = function ( sb , formals , grammarInterval ) {
sb . append ( 'this.' + this . constructor . name . toLowerCase ( ) + '(' ) ;
this . expr . outputRecipe ( sb , formals , grammarInterval ) ;
sb . append ( ')' + getIntervalInfo ( this , grammarInterval ) ) ;
} ;
pexprs . Lookahead . prototype . outputRecipe = function ( sb , formals , grammarInterval ) {
sb . append ( 'this.la(' ) ;
this . expr . outputRecipe ( sb , formals , grammarInterval ) ;
sb . append ( ')' + getIntervalInfo ( this , grammarInterval ) ) ;
} ;
pexprs . Apply . prototype . outputRecipe = function ( sb , formals , grammarInterval ) {
sb . append ( 'this.app(' ) ;
sb . append ( JSON . stringify ( this . ruleName ) ) ;
if ( this . ruleName . indexOf ( '_' ) >= 0 && formals . length > 0 ) {
var apps = formals .
map ( function ( _ , idx ) { return 'this.param(' + idx + ')' ; } ) ;
sb . append ( ', [' + apps . join ( ', ' ) + ']' ) ;
} else if ( this . args . length > 0 ) {
sb . append ( ', [' ) ;
this . args . forEach ( function ( arg , idx ) {
if ( idx > 0 ) {
sb . append ( ', ' ) ;
}
arg . outputRecipe ( sb , formals , grammarInterval ) ;
} ) ;
sb . append ( ']' ) ;
}
sb . append ( ')' + getIntervalInfo ( this , grammarInterval ) ) ;
2016-04-06 16:22:30 +00:00
} ;
2016-05-16 17:27:46 +00:00
} , { "./common" : 48 , "./pexprs" : 67 } ] , 62 : [ function ( require , module , exports ) {
2016-04-06 16:22:30 +00:00
'use strict' ;
// --------------------------------------------------------------------
// Imports
// --------------------------------------------------------------------
var common = require ( './common' ) ;
var pexprs = require ( './pexprs' ) ;
// --------------------------------------------------------------------
// Operations
// --------------------------------------------------------------------
/ *
Returns a PExpr that results from recursively replacing every formal parameter ( i . e . , instance
of ` Param ` ) inside this PExpr with its actual value from ` actuals ` ( an Array ) .
The receiver must not be modified ; a new PExpr must be returned if any replacement is necessary .
* /
2017-02-20 22:19:56 +00:00
pexprs . PExpr . prototype . substituteParams = common . abstract ; // function(actuals) { ... }
2016-04-06 16:22:30 +00:00
pexprs . any . substituteParams =
pexprs . end . substituteParams =
2016-05-16 17:27:46 +00:00
pexprs . Terminal . prototype . substituteParams =
2016-04-06 16:22:30 +00:00
pexprs . Range . prototype . substituteParams =
2016-05-16 17:27:46 +00:00
pexprs . Terminal . prototype . substituteParams =
2016-04-06 16:22:30 +00:00
pexprs . UnicodeChar . prototype . substituteParams = function ( actuals ) {
return this ;
} ;
pexprs . Param . prototype . substituteParams = function ( actuals ) {
return actuals [ this . index ] ;
} ;
pexprs . Alt . prototype . substituteParams = function ( actuals ) {
return new pexprs . Alt (
this . terms . map ( function ( term ) { return term . substituteParams ( actuals ) ; } ) ) ;
} ;
pexprs . Seq . prototype . substituteParams = function ( actuals ) {
return new pexprs . Seq (
this . factors . map ( function ( factor ) { return factor . substituteParams ( actuals ) ; } ) ) ;
} ;
pexprs . Iter . prototype . substituteParams =
pexprs . Not . prototype . substituteParams =
pexprs . Lookahead . prototype . substituteParams =
2016-05-16 17:27:46 +00:00
pexprs . Lex . prototype . substituteParams = function ( actuals ) {
2016-04-06 16:22:30 +00:00
return new this . constructor ( this . expr . substituteParams ( actuals ) ) ;
} ;
pexprs . Apply . prototype . substituteParams = function ( actuals ) {
if ( this . args . length === 0 ) {
// Avoid making a copy of this application, as an optimization
return this ;
} else {
var args = this . args . map ( function ( arg ) { return arg . substituteParams ( actuals ) ; } ) ;
return new pexprs . Apply ( this . ruleName , args ) ;
}
} ;
2016-05-16 17:27:46 +00:00
} , { "./common" : 48 , "./pexprs" : 67 } ] , 63 : [ function ( require , module , exports ) {
2016-05-02 21:15:05 +00:00
'use strict' ;
// --------------------------------------------------------------------
// Imports
// --------------------------------------------------------------------
var common = require ( './common' ) ;
var pexprs = require ( './pexprs' ) ;
var copyWithoutDuplicates = common . copyWithoutDuplicates ;
// --------------------------------------------------------------------
// Operations
// --------------------------------------------------------------------
/ *
Returns a list of strings that will be used as the default argument names for its receiver
( a pexpr ) in a semantic action . This is used exclusively by the Semantics Editor .
` firstArgIndex ` is the 1 - based index of the first argument name that will be generated for this
pexpr . It enables us to name arguments positionally , e . g . , if the second argument is a
non - alphanumeric terminal like "+" , it will be named '$2' .
Here is a more elaborate example that illustrates how this method works :
` (a "+" b).toArgumentNameList(1) ` evaluates to ` ['a', ' $ 2', 'b'] ` with the following recursive
calls :
( a ) . toArgumentNameList ( 1 ) - > [ 'a' ] ,
( "+" ) . toArgumentNameList ( 2 ) - > [ '$2' ] ,
( b ) . toArgumentNameList ( 3 ) - > [ 'b' ]
Notes :
* This method must only be called on well - formed expressions , e . g . , the receiver must
not have any Alt sub - expressions with inconsistent arities .
* e . getArity ( ) === e . toArgumentNameList ( 1 ) . length
* /
2017-02-20 22:19:56 +00:00
pexprs . PExpr . prototype . toArgumentNameList = common . abstract ; // function(firstArgIndex) { ... }
2016-05-02 21:15:05 +00:00
2016-08-07 19:41:10 +00:00
pexprs . any . toArgumentNameList = function ( firstArgIndex ) {
2016-05-02 21:15:05 +00:00
return [ 'any' ] ;
} ;
2016-08-07 19:41:10 +00:00
pexprs . end . toArgumentNameList = function ( firstArgIndex ) {
2016-05-02 21:15:05 +00:00
return [ 'end' ] ;
} ;
2016-08-07 19:41:10 +00:00
pexprs . Terminal . prototype . toArgumentNameList = function ( firstArgIndex ) {
2016-05-02 21:15:05 +00:00
if ( typeof this . obj === 'string' && /^[_a-zA-Z0-9]+$/ . test ( this . obj ) ) {
// If this terminal is a valid suffix for a JS identifier, just prepend it with '_'
return [ '_' + this . obj ] ;
} else {
// Otherwise, name it positionally.
return [ '$' + firstArgIndex ] ;
}
} ;
2016-08-07 19:41:10 +00:00
pexprs . Range . prototype . toArgumentNameList = function ( firstArgIndex ) {
return [ this . from + '_to_' + this . to ] ;
2016-05-02 21:15:05 +00:00
} ;
2016-08-07 19:41:10 +00:00
pexprs . Alt . prototype . toArgumentNameList = function ( firstArgIndex ) {
2016-05-02 21:15:05 +00:00
// `termArgNameLists` is an array of arrays where each row is the
// argument name list that corresponds to a term in this alternation.
var termArgNameLists = this . terms . map ( function ( term ) {
2016-08-07 19:41:10 +00:00
return term . toArgumentNameList ( firstArgIndex ) ;
2016-05-02 21:15:05 +00:00
} ) ;
var argumentNameList = [ ] ;
var numArgs = termArgNameLists [ 0 ] . length ;
for ( var colIdx = 0 ; colIdx < numArgs ; colIdx ++ ) {
var col = [ ] ;
for ( var rowIdx = 0 ; rowIdx < this . terms . length ; rowIdx ++ ) {
col . push ( termArgNameLists [ rowIdx ] [ colIdx ] ) ;
}
var uniqueNames = copyWithoutDuplicates ( col ) ;
argumentNameList . push ( uniqueNames . join ( '_or_' ) ) ;
}
return argumentNameList ;
} ;
2016-08-07 19:41:10 +00:00
pexprs . Seq . prototype . toArgumentNameList = function ( firstArgIndex ) {
2016-05-02 21:15:05 +00:00
// Generate the argument name list, without worrying about duplicates.
var argumentNameList = [ ] ;
this . factors . forEach ( function ( factor ) {
2016-08-07 19:41:10 +00:00
var factorArgumentNameList = factor . toArgumentNameList ( firstArgIndex ) ;
2016-05-02 21:15:05 +00:00
argumentNameList = argumentNameList . concat ( factorArgumentNameList ) ;
// Shift the firstArgIndex to take this factor's argument names into account.
firstArgIndex += factorArgumentNameList . length ;
} ) ;
2016-08-07 19:41:10 +00:00
// `count` is used to record the number of times each argument name occurs in the list,
// this is useful for checking duplicated argument name. It maps argument names to ints.
var count = Object . create ( null ) ;
argumentNameList . forEach ( function ( argName ) {
count [ argName ] = ( count [ argName ] || 0 ) + 1 ;
} ) ;
// Append subscripts ('_1', '_2', ...) to duplicate argument names.
Object . keys ( count ) . forEach ( function ( dupArgName ) {
if ( count [ dupArgName ] <= 1 ) {
return ;
}
// This name shows up more than once, so add subscripts.
var subscript = 1 ;
argumentNameList . forEach ( function ( argName , idx ) {
if ( argName === dupArgName ) {
argumentNameList [ idx ] = argName + '_' + subscript ++ ;
}
2016-07-11 16:06:07 +00:00
} ) ;
2016-08-07 19:41:10 +00:00
} ) ;
2016-07-11 16:06:07 +00:00
return argumentNameList ;
2016-05-02 21:15:05 +00:00
} ;
2016-08-07 19:41:10 +00:00
pexprs . Iter . prototype . toArgumentNameList = function ( firstArgIndex ) {
return this . expr . toArgumentNameList ( firstArgIndex ) . map ( function ( exprArgumentString ) {
return exprArgumentString [ exprArgumentString . length - 1 ] === 's' ?
exprArgumentString + 'es' :
exprArgumentString + 's' ;
} ) ;
} ;
pexprs . Opt . prototype . toArgumentNameList = function ( firstArgIndex ) {
return this . expr . toArgumentNameList ( firstArgIndex ) . map ( function ( argName ) {
2016-05-02 21:15:05 +00:00
return 'opt' + argName [ 0 ] . toUpperCase ( ) + argName . slice ( 1 ) ;
} ) ;
} ;
2016-08-07 19:41:10 +00:00
pexprs . Not . prototype . toArgumentNameList = function ( firstArgIndex ) {
2016-05-02 21:15:05 +00:00
return [ ] ;
} ;
pexprs . Lookahead . prototype . toArgumentNameList =
2016-08-07 19:41:10 +00:00
pexprs . Lex . prototype . toArgumentNameList = function ( firstArgIndex ) {
return this . expr . toArgumentNameList ( firstArgIndex ) ;
2016-05-02 21:15:05 +00:00
} ;
2016-08-07 19:41:10 +00:00
pexprs . Apply . prototype . toArgumentNameList = function ( firstArgIndex ) {
2016-05-02 21:15:05 +00:00
return [ this . ruleName ] ;
} ;
2016-08-07 19:41:10 +00:00
pexprs . UnicodeChar . prototype . toArgumentNameList = function ( firstArgIndex ) {
return '$' + firstArgIndex ;
2016-05-02 21:15:05 +00:00
} ;
// "Value pexprs" (Value, Str, Arr, Obj) are going away soon, so we don't worry about them here.
2016-05-16 17:27:46 +00:00
} , { "./common" : 48 , "./pexprs" : 67 } ] , 64 : [ function ( require , module , exports ) {
2016-04-06 16:22:30 +00:00
'use strict' ;
// --------------------------------------------------------------------
// Imports
// --------------------------------------------------------------------
var common = require ( './common' ) ;
var pexprs = require ( './pexprs' ) ;
// --------------------------------------------------------------------
// Operations
// --------------------------------------------------------------------
// Returns a string representing the PExpr, for use as a UI label, etc.
2017-02-20 22:19:56 +00:00
pexprs . PExpr . prototype . toDisplayString = common . abstract ;
2016-04-06 16:22:30 +00:00
pexprs . Alt . prototype . toDisplayString =
pexprs . Seq . prototype . toDisplayString =
pexprs . Iter . prototype . toDisplayString =
pexprs . Not . prototype . toDisplayString =
pexprs . Lookahead . prototype . toDisplayString =
2016-05-16 17:27:46 +00:00
pexprs . Lex . prototype . toDisplayString = function ( ) {
2016-04-06 16:22:30 +00:00
if ( this . interval ) {
return this . interval . trimmed ( ) . contents ;
}
return '[' + this . constructor . name + ']' ;
} ;
pexprs . any . toDisplayString = function ( ) {
return 'any' ;
} ;
pexprs . end . toDisplayString = function ( ) {
return 'end' ;
} ;
2016-05-16 17:27:46 +00:00
pexprs . Terminal . prototype . toDisplayString = function ( ) {
2016-04-06 16:22:30 +00:00
return JSON . stringify ( this . obj ) ;
} ;
pexprs . Range . prototype . toDisplayString = function ( ) {
return JSON . stringify ( this . from ) + '..' + JSON . stringify ( this . to ) ;
} ;
pexprs . Param . prototype . toDisplayString = function ( ) {
return '#' + this . index ;
} ;
pexprs . Apply . prototype . toDisplayString = function ( ) {
return this . toString ( ) ;
} ;
pexprs . UnicodeChar . prototype . toDisplayString = function ( ) {
return 'Unicode {' + this . category + '} character' ;
} ;
2016-05-16 17:27:46 +00:00
} , { "./common" : 48 , "./pexprs" : 67 } ] , 65 : [ function ( require , module , exports ) {
2016-04-06 16:22:30 +00:00
'use strict' ;
// --------------------------------------------------------------------
// Imports
// --------------------------------------------------------------------
var Failure = require ( './Failure' ) ;
var common = require ( './common' ) ;
var pexprs = require ( './pexprs' ) ;
// --------------------------------------------------------------------
// Operations
// --------------------------------------------------------------------
2017-02-20 22:19:56 +00:00
pexprs . PExpr . prototype . toFailure = common . abstract ;
2016-04-06 16:22:30 +00:00
pexprs . any . toFailure = function ( grammar ) {
2016-08-07 19:41:10 +00:00
return new Failure ( 'any object' , 'description' ) ;
2016-04-06 16:22:30 +00:00
} ;
pexprs . end . toFailure = function ( grammar ) {
2016-08-07 19:41:10 +00:00
return new Failure ( 'end of input' , 'description' ) ;
2016-04-06 16:22:30 +00:00
} ;
2016-05-16 17:27:46 +00:00
pexprs . Terminal . prototype . toFailure = function ( grammar ) {
2016-08-07 19:41:10 +00:00
return typeof this . obj === 'string' ?
new Failure ( this . obj , 'string' ) :
new Failure ( JSON . stringify ( this . obj ) , 'code' ) ;
2016-04-06 16:22:30 +00:00
} ;
pexprs . Range . prototype . toFailure = function ( grammar ) {
// TODO: come up with something better
2016-08-07 19:41:10 +00:00
return new Failure ( JSON . stringify ( this . from ) + '..' + JSON . stringify ( this . to ) , 'code' ) ;
2016-04-06 16:22:30 +00:00
} ;
pexprs . Not . prototype . toFailure = function ( grammar ) {
var description = this . expr === pexprs . any ?
'nothing' :
'not ' + this . expr . toFailure ( grammar ) ;
2016-08-07 19:41:10 +00:00
return new Failure ( description , 'description' ) ;
2016-04-06 16:22:30 +00:00
} ;
2016-08-07 19:41:10 +00:00
// TODO: think about Arr, Str, and Obj
2016-04-06 16:22:30 +00:00
pexprs . Apply . prototype . toFailure = function ( grammar ) {
var description = grammar . ruleDescriptions [ this . ruleName ] ;
if ( ! description ) {
var article = ( /^[aeiouAEIOU]/ . test ( this . ruleName ) ? 'an' : 'a' ) ;
description = article + ' ' + this . ruleName ;
}
2016-08-07 19:41:10 +00:00
return new Failure ( description , 'description' ) ;
2016-04-06 16:22:30 +00:00
} ;
pexprs . UnicodeChar . prototype . toFailure = function ( grammar ) {
2016-08-07 19:41:10 +00:00
return new Failure ( this . toDisplayString ( ) , 'description' ) ;
2016-04-06 16:22:30 +00:00
} ;
2016-05-16 17:27:46 +00:00
} , { "./Failure" : 37 , "./common" : 48 , "./pexprs" : 67 } ] , 66 : [ function ( require , module , exports ) {
2016-04-06 16:22:30 +00:00
'use strict' ;
// --------------------------------------------------------------------
// Imports
// --------------------------------------------------------------------
var common = require ( './common' ) ;
var pexprs = require ( './pexprs' ) ;
// --------------------------------------------------------------------
// Operations
// --------------------------------------------------------------------
/ *
e1 . toString ( ) === e2 . toString ( ) == > e1 and e2 are semantically equivalent .
Note that this is not an iff ( <= => ) : e . g . ,
( ~ "b" "a" ) . toString ( ) !== ( "a" ) . toString ( ) , even though
~ "b" "a" and "a" are interchangeable in any grammar ,
both in terms of the languages they accept and their arities .
* /
2017-02-20 22:19:56 +00:00
pexprs . PExpr . prototype . toString = common . abstract ;
2016-04-06 16:22:30 +00:00
pexprs . any . toString = function ( ) {
return 'any' ;
} ;
pexprs . end . toString = function ( ) {
return 'end' ;
} ;
2016-05-16 17:27:46 +00:00
pexprs . Terminal . prototype . toString = function ( ) {
2016-04-06 16:22:30 +00:00
return JSON . stringify ( this . obj ) ;
} ;
pexprs . Range . prototype . toString = function ( ) {
return JSON . stringify ( this . from ) + '..' + JSON . stringify ( this . to ) ;
} ;
pexprs . Param . prototype . toString = function ( ) {
return '$' + this . index ;
} ;
pexprs . Lex . prototype . toString = function ( ) {
return '#(' + this . expr . toString ( ) + ')' ;
} ;
pexprs . Alt . prototype . toString = function ( ) {
return this . terms . length === 1 ?
this . terms [ 0 ] . toString ( ) :
'(' + this . terms . map ( function ( term ) { return term . toString ( ) ; } ) . join ( ' | ' ) + ')' ;
} ;
pexprs . Seq . prototype . toString = function ( ) {
return this . factors . length === 1 ?
this . factors [ 0 ] . toString ( ) :
'(' + this . factors . map ( function ( factor ) { return factor . toString ( ) ; } ) . join ( ' ' ) + ')' ;
} ;
pexprs . Iter . prototype . toString = function ( ) {
return this . expr + this . operator ;
} ;
pexprs . Not . prototype . toString = function ( ) {
return '~' + this . expr ;
} ;
pexprs . Lookahead . prototype . toString = function ( ) {
return '&' + this . expr ;
} ;
pexprs . Apply . prototype . toString = function ( ) {
if ( this . args . length > 0 ) {
var ps = this . args . map ( function ( arg ) { return arg . toString ( ) ; } ) ;
return this . ruleName + '<' + ps . join ( ',' ) + '>' ;
} else {
return this . ruleName ;
}
} ;
pexprs . UnicodeChar . prototype . toString = function ( ) {
return '\\p{' + this . category + '}' ;
} ;
2016-05-16 17:27:46 +00:00
} , { "./common" : 48 , "./pexprs" : 67 } ] , 67 : [ function ( require , module , exports ) {
2016-04-06 16:22:30 +00:00
'use strict' ;
// --------------------------------------------------------------------
// Imports
// --------------------------------------------------------------------
var UnicodeCategories = require ( '../third_party/UnicodeCategories' ) ;
var common = require ( './common' ) ;
var errors = require ( './errors' ) ;
var inherits = require ( 'inherits' ) ;
// --------------------------------------------------------------------
// Private stuff
// --------------------------------------------------------------------
// General stuff
function PExpr ( ) {
throw new Error ( "PExpr cannot be instantiated -- it's abstract" ) ;
}
// Set the `interval` property to the interval containing the source for this expression.
PExpr . prototype . withInterval = function ( interval ) {
if ( interval ) {
this . interval = interval . trimmed ( ) ;
}
return this ;
} ;
// Any
var any = Object . create ( PExpr . prototype ) ;
// End
var end = Object . create ( PExpr . prototype ) ;
2016-05-16 17:27:46 +00:00
// Terminals
2016-04-06 16:22:30 +00:00
2016-05-16 17:27:46 +00:00
function Terminal ( obj ) {
2016-04-06 16:22:30 +00:00
this . obj = obj ;
}
2016-05-16 17:27:46 +00:00
inherits ( Terminal , PExpr ) ;
2016-04-06 16:22:30 +00:00
// Ranges
function Range ( from , to ) {
this . from = from ;
this . to = to ;
}
inherits ( Range , PExpr ) ;
// Parameters
function Param ( index ) {
this . index = index ;
}
inherits ( Param , PExpr ) ;
// Alternation
function Alt ( terms ) {
this . terms = terms ;
}
inherits ( Alt , PExpr ) ;
// Extend is an implementation detail of rule extension
function Extend ( superGrammar , name , body ) {
this . superGrammar = superGrammar ;
this . name = name ;
this . body = body ;
var origBody = superGrammar . ruleBodies [ name ] ;
this . terms = [ body , origBody ] ;
}
inherits ( Extend , Alt ) ;
// Sequences
function Seq ( factors ) {
this . factors = factors ;
}
inherits ( Seq , PExpr ) ;
// Iterators and optionals
function Iter ( expr ) {
this . expr = expr ;
}
inherits ( Iter , PExpr ) ;
function Star ( expr ) {
this . expr = expr ;
}
inherits ( Star , Iter ) ;
function Plus ( expr ) {
this . expr = expr ;
}
inherits ( Plus , Iter ) ;
function Opt ( expr ) {
this . expr = expr ;
}
inherits ( Opt , Iter ) ;
Star . prototype . operator = '*' ;
Plus . prototype . operator = '+' ;
Opt . prototype . operator = '?' ;
Star . prototype . minNumMatches = 0 ;
Plus . prototype . minNumMatches = 1 ;
Opt . prototype . minNumMatches = 0 ;
Star . prototype . maxNumMatches = Number . POSITIVE _INFINITY ;
Plus . prototype . maxNumMatches = Number . POSITIVE _INFINITY ;
Opt . prototype . maxNumMatches = 1 ;
// Predicates
function Not ( expr ) {
this . expr = expr ;
}
inherits ( Not , PExpr ) ;
function Lookahead ( expr ) {
this . expr = expr ;
}
inherits ( Lookahead , PExpr ) ;
// "Lexification"
function Lex ( expr ) {
this . expr = expr ;
}
inherits ( Lex , PExpr ) ;
// Array decomposition
function Arr ( expr ) {
this . expr = expr ;
}
inherits ( Arr , PExpr ) ;
// String decomposition
function Str ( expr ) {
this . expr = expr ;
}
inherits ( Str , PExpr ) ;
// Object decomposition
function Obj ( properties , isLenient ) {
var names = properties . map ( function ( property ) { return property . name ; } ) ;
var duplicates = common . getDuplicates ( names ) ;
if ( duplicates . length > 0 ) {
throw errors . duplicatePropertyNames ( duplicates ) ;
} else {
this . properties = properties ;
this . isLenient = isLenient ;
}
}
inherits ( Obj , PExpr ) ;
// Rule application
function Apply ( ruleName , optArgs ) {
this . ruleName = ruleName ;
this . args = optArgs || [ ] ;
}
inherits ( Apply , PExpr ) ;
Apply . prototype . isSyntactic = function ( ) {
return common . isSyntactic ( this . ruleName ) ;
} ;
// This method just caches the result of `this.toString()` in a non-enumerable property.
Apply . prototype . toMemoKey = function ( ) {
if ( ! this . _memoKey ) {
Object . defineProperty ( this , '_memoKey' , { value : this . toString ( ) } ) ;
}
return this . _memoKey ;
} ;
// Unicode character
2016-05-02 21:15:05 +00:00
2016-04-06 16:22:30 +00:00
function UnicodeChar ( category ) {
this . category = category ;
this . pattern = UnicodeCategories [ category ] ;
}
inherits ( UnicodeChar , PExpr ) ;
// --------------------------------------------------------------------
// Exports
// --------------------------------------------------------------------
exports . PExpr = PExpr ;
exports . any = any ;
exports . end = end ;
2016-05-16 17:27:46 +00:00
exports . Terminal = Terminal ;
2016-04-06 16:22:30 +00:00
exports . Range = Range ;
exports . Param = Param ;
exports . Alt = Alt ;
exports . Extend = Extend ;
exports . Seq = Seq ;
exports . Iter = Iter ;
exports . Star = Star ;
exports . Plus = Plus ;
exports . Opt = Opt ;
exports . Not = Not ;
exports . Lookahead = Lookahead ;
exports . Lex = Lex ;
exports . Arr = Arr ;
exports . Str = Str ;
exports . Obj = Obj ;
exports . Apply = Apply ;
exports . UnicodeChar = UnicodeChar ;
// --------------------------------------------------------------------
// Extensions
// --------------------------------------------------------------------
2016-05-02 21:15:05 +00:00
require ( './pexprs-allowsSkippingPrecedingSpace' ) ;
2016-04-06 16:22:30 +00:00
require ( './pexprs-assertAllApplicationsAreValid' ) ;
require ( './pexprs-assertChoicesHaveUniformArity' ) ;
require ( './pexprs-assertIteratedExprsAreNotNullable' ) ;
require ( './pexprs-check' ) ;
require ( './pexprs-eval' ) ;
require ( './pexprs-getArity' ) ;
require ( './pexprs-outputRecipe' ) ;
require ( './pexprs-introduceParams' ) ;
require ( './pexprs-isNullable' ) ;
require ( './pexprs-substituteParams' ) ;
require ( './pexprs-toDisplayString' ) ;
2016-05-02 21:15:05 +00:00
require ( './pexprs-toArgumentNameList' ) ;
2016-04-06 16:22:30 +00:00
require ( './pexprs-toFailure' ) ;
require ( './pexprs-toString' ) ;
2016-05-16 17:27:46 +00:00
} , { "../third_party/UnicodeCategories" : 69 , "./common" : 48 , "./errors" : 49 , "./pexprs-allowsSkippingPrecedingSpace" : 52 , "./pexprs-assertAllApplicationsAreValid" : 53 , "./pexprs-assertChoicesHaveUniformArity" : 54 , "./pexprs-assertIteratedExprsAreNotNullable" : 55 , "./pexprs-check" : 56 , "./pexprs-eval" : 57 , "./pexprs-getArity" : 58 , "./pexprs-introduceParams" : 59 , "./pexprs-isNullable" : 60 , "./pexprs-outputRecipe" : 61 , "./pexprs-substituteParams" : 62 , "./pexprs-toArgumentNameList" : 63 , "./pexprs-toDisplayString" : 64 , "./pexprs-toFailure" : 65 , "./pexprs-toString" : 66 , "inherits" : 33 } ] , 68 : [ function ( require , module , exports ) {
2016-04-06 16:22:30 +00:00
'use strict' ;
// --------------------------------------------------------------------
// Imports
// --------------------------------------------------------------------
var common = require ( './common' ) ;
// --------------------------------------------------------------------
// Private stuff
// --------------------------------------------------------------------
// Given an array of numbers `arr`, return an array of the numbers as strings,
// right-justified and padded to the same length.
function padNumbersToEqualLength ( arr ) {
var maxLen = 0 ;
var strings = arr . map ( function ( n ) {
var str = n . toString ( ) ;
maxLen = Math . max ( maxLen , str . length ) ;
return str ;
} ) ;
return strings . map ( function ( s ) { return common . padLeft ( s , maxLen ) ; } ) ;
}
// Produce a new string that would be the result of copying the contents
// of the string `src` onto `dest` at offset `offest`.
function strcpy ( dest , src , offset ) {
var origDestLen = dest . length ;
var start = dest . slice ( 0 , offset ) ;
var end = dest . slice ( offset + src . length ) ;
return ( start + src + end ) . substr ( 0 , origDestLen ) ;
}
// --------------------------------------------------------------------
// Exports
// --------------------------------------------------------------------
// Return an object with the line and column information for the given
// offset in `str`.
exports . getLineAndColumn = function ( str , offset ) {
var lineNum = 1 ;
var colNum = 1 ;
var currOffset = 0 ;
var lineStartOffset = 0 ;
var nextLine = null ;
var prevLine = null ;
var prevLineStartOffset = - 1 ;
while ( currOffset < offset ) {
var c = str . charAt ( currOffset ++ ) ;
if ( c === '\n' ) {
lineNum ++ ;
colNum = 1 ;
prevLineStartOffset = lineStartOffset ;
lineStartOffset = currOffset ;
} else if ( c !== '\r' ) {
colNum ++ ;
}
}
// Find the end of the target line.
var lineEndOffset = str . indexOf ( '\n' , lineStartOffset ) ;
if ( lineEndOffset === - 1 ) {
lineEndOffset = str . length ;
} else {
// Get the next line.
var nextLineEndOffset = str . indexOf ( '\n' , lineEndOffset + 1 ) ;
nextLine = nextLineEndOffset === - 1 ? str . slice ( lineEndOffset )
: str . slice ( lineEndOffset , nextLineEndOffset ) ;
// Strip leading and trailing EOL char(s).
nextLine = nextLine . replace ( /^\r?\n/ , '' ) . replace ( /\r$/ , '' ) ;
}
// Get the previous line.
if ( prevLineStartOffset >= 0 ) {
prevLine = str . slice ( prevLineStartOffset , lineStartOffset )
. replace ( /\r?\n$/ , '' ) ; // Strip trailing EOL char(s).
}
// Get the target line, stripping a trailing carriage return if necessary.
var line = str . slice ( lineStartOffset , lineEndOffset ) . replace ( /\r$/ , '' ) ;
return {
lineNum : lineNum ,
colNum : colNum ,
line : line ,
prevLine : prevLine ,
nextLine : nextLine
} ;
} ;
// Return a nicely-formatted string describing the line and column for the
// given offset in `str`.
exports . getLineAndColumnMessage = function ( str , offset /* ...ranges */ ) {
var repeatStr = common . repeatStr ;
var lineAndCol = exports . getLineAndColumn ( str , offset ) ;
var sb = new common . StringBuffer ( ) ;
sb . append ( 'Line ' + lineAndCol . lineNum + ', col ' + lineAndCol . colNum + ':\n' ) ;
// An array of the previous, current, and next line numbers as strings of equal length.
var lineNumbers = padNumbersToEqualLength ( [
lineAndCol . prevLine == null ? 0 : lineAndCol . lineNum - 1 ,
lineAndCol . lineNum ,
lineAndCol . nextLine == null ? 0 : lineAndCol . lineNum + 1
] ) ;
// Helper for appending formatting input lines to the buffer.
function appendLine ( num , content , prefix ) {
sb . append ( prefix + lineNumbers [ num ] + ' | ' + content + '\n' ) ;
}
// Include the previous line for context if possible.
if ( lineAndCol . prevLine != null ) {
appendLine ( 0 , lineAndCol . prevLine , ' ' ) ;
}
// Line that the error occurred on.
appendLine ( 1 , lineAndCol . line , '> ' ) ;
// Build up the line that points to the offset and possible indicates one or more ranges.
// Start with a blank line, and indicate each range by overlaying a string of `~` chars.
var lineLen = lineAndCol . line . length ;
var indicationLine = repeatStr ( ' ' , lineLen + 1 ) ;
var ranges = Array . prototype . slice . call ( arguments , 2 ) ;
for ( var i = 0 ; i < ranges . length ; ++ i ) {
var startIdx = ranges [ i ] [ 0 ] ;
var endIdx = ranges [ i ] [ 1 ] ;
common . assert ( startIdx >= 0 && startIdx <= endIdx , 'range start must be >= 0 and <= end' ) ;
var lineStartOffset = offset - lineAndCol . colNum + 1 ;
startIdx = Math . max ( 0 , startIdx - lineStartOffset ) ;
endIdx = Math . min ( endIdx - lineStartOffset , lineLen ) ;
indicationLine = strcpy ( indicationLine , repeatStr ( '~' , endIdx - startIdx ) , startIdx ) ;
}
var gutterWidth = 2 + lineNumbers [ 1 ] . length + 3 ;
sb . append ( repeatStr ( ' ' , gutterWidth ) ) ;
indicationLine = strcpy ( indicationLine , '^' , lineAndCol . colNum - 1 ) ;
sb . append ( indicationLine . replace ( / +$/ , '' ) + '\n' ) ;
// Include the next line for context if possible.
if ( lineAndCol . nextLine != null ) {
appendLine ( 2 , lineAndCol . nextLine , ' ' ) ;
}
return sb . contents ( ) ;
} ;
2016-05-16 17:27:46 +00:00
} , { "./common" : 48 } ] , 69 : [ function ( require , module , exports ) {
2016-04-06 16:22:30 +00:00
// Based on https://github.com/tvcutsem/es-lab/blob/master/src/parser/unicode.js.
// These are just categories that are used in ES5.
// The full list of Unicode categories is here: http://www.fileformat.info/info/unicode/category/index.htm.
module . exports = {
// Letters
Lu : / [ \ u 0 0 4 1 - \ u 0 0 5 A ] | [ \ u 0 0 C 0 - \ u 0 0 D 6 ] | [ \ u 0 0 D 8 - \ u 0 0 D E ] | [ \ u 0 1 0 0 - \ u 0 1 0 0 ] | [ \ u 0 1 0 2 - \ u 0 1 0 2 ] | [ \ u 0 1 0 4 - \ u 0 1 0 4 ] | [ \ u 0 1 0 6 - \ u 0 1 0 6 ] | [ \ u 0 1 0 8 - \ u 0 1 0 8 ] | [ \ u 0 1 0 A - \ u 0 1 0 A ] | [ \ u 0 1 0 C - \ u 0 1 0 C ] | [ \ u 0 1 0 E - \ u 0 1 0 E ] | [ \ u 0 1 1 0 - \ u 0 1 1 0 ] | [ \ u 0 1 1 2 - \ u 0 1 1 2 ] | [ \ u 0 1 1 4 - \ u 0 1 1 4 ] | [ \ u 0 1 1 6 - \ u 0 1 1 6 ] | [ \ u 0 1 1 8 - \ u 0 1 1 8 ] | [ \ u 0 1 1 A - \ u 0 1 1 A ] | [ \ u 0 1 1 C - \ u 0 1 1 C ] | [ \ u 0 1 1 E - \ u 0 1 1 E ] | [ \ u 0 1 2 0 - \ u 0 1 2 0 ] | [ \ u 0 1 2 2 - \ u 0 1 2 2 ] | [ \ u 0 1 2 4 - \ u 0 1 2 4 ] | [ \ u 0 1 2 6 - \ u 0 1 2 6 ] | [ \ u 0 1 2 8 - \ u 0 1 2 8 ] | [ \ u 0 1 2 A - \ u 0 1 2 A ] | [ \ u 0 1 2 C - \ u 0 1 2 C ] | [ \ u 0 1 2 E - \ u 0 1 2 E ] | [ \ u 0 1 3 0 - \ u 0 1 3 0 ] | [ \ u 0 1 3 2 - \ u 0 1 3 2 ] | [ \ u 0 1 3 4 - \ u 0 1 3 4 ] | [ \ u 0 1 3 6 - \ u 0 1 3 6 ] | [ \ u 0 1 3 9 - \ u 0 1 3 9 ] | [ \ u 0 1 3 B - \ u 0 1 3 B ] | [ \ u 0 1 3 D - \ u 0 1 3 D ] | [ \ u 0 1 3 F - \ u 0 1 3 F ] | [ \ u 0 1 4 1 - \ u 0 1 4 1 ] | [ \ u 0 1 4 3 - \ u 0 1 4 3 ] | [ \ u 0 1 4 5 - \ u 0 1 4 5 ] | [ \ u 0 1 4 7 - \ u 0 1 4 7 ] | [ \ u 0 1 4 A - \ u 0 1 4 A ] | [ \ u 0 1 4 C - \ u 0 1 4 C ] | [ \ u 0 1 4 E - \ u 0 1 4 E ] | [ \ u 0 1 5 0 - \ u 0 1 5 0 ] | [ \ u 0 1 5 2 - \ u 0 1 5 2 ] | [ \ u 0 1 5 4 - \ u 0 1 5 4 ] | [ \ u 0 1 5 6 - \ u 0 1 5 6 ] | [ \ u 0 1 5 8 - \ u 0 1 5 8 ] | [ \ u 0 1 5 A - \ u 0 1 5 A ] | [ \ u 0 1 5 C - \ u 0 1 5 C ] | [ \ u 0 1 5 E - \ u 0 1 5 E ] | [ \ u 0 1 6 0 - \ u 0 1 6 0 ] | [ \ u 0 1 6 2 - \ u 0 1 6 2 ] | [ \ u 0 1 6 4 - \ u 0 1 6 4 ] | [ \ u 0 1 6 6 - \ u 0 1 6 6 ] | [ \ u 0 1 6 8 - \ u 0 1 6 8 ] | [ \ u 0 1 6 A - \ u 0 1 6 A ] | [ \ u 0 1 6 C - \ u 0 1 6 C ] | [ \ u 0 1 6 E - \ u 0 1 6 E ] | [ \ u 0 1 7 0 - \ u 0 1 7 0 ] | [ \ u 0 1 7 2 - \ u 0 1 7 2 ] | [ \ u 0 1 7 4 - \ u 0 1 7 4 ] | [ \ u 0 1 7 6 - \ u 0 1 7 6 ] | [ \ u 0 1 7 8 - \ u 0 1 7 9 ] | [ \ u 0 1 7 B - \ u 0 1 7 B ] | [ \ u 0 1 7 D - \ u 0 1 7 D ] | [ \ u 0 1 8 1 - \ u 0 1 8 2 ] | [ \ u 0 1 8 4 - \ u 0 1 8 4 ] | [ \ u 0 1 8 6 - \ u 0 1 8 7 ] | [ \ u 0 1 8 9 - \ u 0 1 8 B ] | [ \ u 0 1 8 E - \ u 0 1 9 1 ] | [ \ u 0 1 9 3 - \ u 0 1 9 4 ] | [ \ u 0 1 9 6 - \ u 0 1 9 8 ] | [ \ u 0 1 9 C - \ u 0 1 9 D ] | [ \ u 0 1 9 F - \ u 0 1 A 0 ] | [ \ u 0 1 A 2 - \ u 0 1 A 2 ] | [ \ u 0 1 A 4 - \ u 0 1 A 4 ] | [ \ u 0 1 A 6 - \ u 0 1 A 7 ] | [ \ u 0 1 A 9 - \ u 0 1 A 9 ] | [ \ u 0 1 A C - \ u 0 1 A C ] | [ \ u 0 1 A E - \ u 0 1 A F ] | [ \ u 0 1 B 1 - \ u 0 1 B 3 ] | [ \ u 0 1 B 5 - \ u 0 1 B 5 ] | [ \ u 0 1 B 7 - \ u 0 1 B 8 ] | [ \ u 0 1 B C - \ u 0 1 B C ] | [ \ u 0 1 C 4 - \ u 0 1 C 4 ] | [ \ u 0 1 C 7 - \ u 0 1 C 7 ] | [ \ u 0 1 C A - \ u 0 1 C A ] | [ \ u 0 1 C D - \ u 0 1 C D ] | [ \ u 0 1 C F - \ u 0 1 C F ] | [ \ u 0 1 D 1 - \ u 0 1 D 1 ] | [ \ u 0 1 D 3 - \ u 0 1 D 3 ] | [ \ u 0 1 D 5 - \ u 0 1 D 5 ] | [ \ u 0 1 D 7 - \ u 0 1 D 7 ] | [ \ u 0 1 D 9 - \ u 0 1 D 9 ] | [ \ u 0 1 D B - \ u 0 1 D B ] | [ \ u 0 1 D E - \ u 0 1 D E ] | [ \ u 0 1 E 0 - \ u 0 1 E 0 ] | [ \ u 0 1 E 2 - \ u 0 1 E 2 ] | [ \ u 0 1 E 4 - \ u 0 1 E 4 ] | [ \ u 0 1 E 6 - \ u 0 1 E 6 ] | [ \ u 0 1 E 8 - \ u 0 1 E 8 ] | [ \ u 0 1 E A - \ u 0 1 E A ] | [ \ u 0 1 E C - \ u 0 1 E C ] | [ \ u 0 1 E E - \ u 0 1 E E ] | [ \ u 0 1 F 1 - \ u 0 1 F 1 ] | [ \ u 0 1 F 4 - \ u 0 1 F 4 ] | [ \ u 0 1 F A - \ u 0 1 F A ] | [ \ u 0 1 F C - \ u 0 1 F C ] | [ \ u 0 1 F E - \ u 0 1 F E ] | [ \ u 0 2 0 0 - \ u 0 2 0 0 ] | [ \ u 0 2 0 2 - \ u 0 2 0 2 ] | [ \ u 0 2 0 4 - \ u 0 2 0 4 ] | [ \ u 0 2 0 6 - \ u 0 2 0 6 ] | [ \ u 0 2 0 8 - \ u 0 2 0 8 ] | [ \ u 0 2 0 A - \ u 0 2 0 A ] | [ \ u 0 2 0 C - \ u 0 2 0 C ] | [ \ u 0 2 0 E - \ u 0 2 0 E ] | [ \ u 0 2 1 0 - \ u 0 2 1 0 ] | [ \ u 0 2 1 2 - \ u 0 2 1 2 ] | [ \ u 0 2 1 4 - \ u 0 2 1 4 ] | [ \ u 0 2 1 6 - \ u 0 2 1 6 ] | [ \ u 0 3 8 6 - \ u 0 3 8 6 ] | [ \ u 0 3 8 8 - \ u 0 3 8 A ] | [ \ u 0 3 8 C - \ u 0 3 8 C ] | [ \ u 0 3 8 E - \ u 0 3 8 F ] | [ \ u 0 3 9 1 - \ u 0 3 A 1 ] | [ \ u 0 3 A 3 - \ u 0 3 A B ] | [ \ u 0 3 D 2 - \ u 0 3 D 4 ] | [ \ u 0 3 D A - \ u 0 3 D A ] | [ \ u 0 3 D C - \ u 0 3 D C ] | [ \ u 0 3 D E - \ u 0 3 D E ] | [ \ u 0 3 E 0 - \ u 0 3 E 0 ] | [ \ u 0 3 E 2 - \ u 0 3 E 2 ] | [ \ u 0 3 E 4 - \ u 0 3 E 4 ] | [ \ u 0 3 E 6 - \ u 0 3 E 6 ] | [ \ u 0 3 E 8 - \ u 0 3 E 8 ] | [ \ u 0 3 E A - \ u 0 3 E A ] | [ \ u 0 3 E C - \ u 0 3 E C ] | [ \ u 0 3 E E - \ u 0 3 E E ] | [ \ u 0 4 0 1 - \ u 0 4 0 C ] | [ \ u 0 4 0 E - \ u 0 4 2 F ] | [ \ u 0 4 6 0 - \ u 0 4 6 0 ] | [ \ u 0 4 6 2 - \ u 0 4 6 2 ] | [ \ u 0 4 6 4 - \ u 0 4 6 4 ] | [ \ u 0 4 6 6 - \ u 0 4 6 6 ] | [ \ u 0 4 6 8 - \ u 0 4 6 8 ] | [ \ u 0 4 6 A - \ u 0 4 6 A ] | [ \ u 0 4 6 C - \ u 0 4 6 C ] | [ \ u 0 4 6 E - \ u 0 4 6 E ] | [ \ u 0 4 7 0 - \ u 0 4 7 0 ] | [ \ u 0 4 7 2 - \ u 0 4 7 2 ] | [ \ u 0 4 7 4 - \ u 0 4 7 4 ] | [ \ u 0 4 7 6 - \ u 0 4 7 6 ] | [ \ u 0 4 7 8 - \ u 0 4 7 8 ] | [ \ u 0 4 7 A - \ u 0 4 7 A ] | [ \ u 0 4 7 C - \ u 0 4 7 C ] | [ \ u 0 4 7 E - \ u 0 4 7 E ] | [ \ u 0 4 8 0 - \ u 0 4 8 0 ] | [ \ u 0 4 9 0 - \ u 0 4 9 0 ] | [ \ u 0 4 9 2 - \ u 0 4 9 2 ] | [ \ u 0 4 9 4 - \ u 0 4 9 4 ] | [ \ u 0 4 9 6 - \ u 0 4 9 6 ] | [ \ u 0 4 9 8 - \ u 0 4 9 8 ] | [ \ u 0 4 9 A - \ u 0 4 9 A ] | [ \ u 0 4 9 C - \ u 0 4 9 C ] | [ \ u 0 4 9 E - \ u 0 4 9 E ] | [ \ u 0 4 A 0 - \ u 0 4 A 0 ] | [ \ u 0 4 A 2 - \ u 0 4 A 2 ] | [ \ u 0 4 A 4 - \ u 0 4 A 4 ] | [ \ u 0 4 A 6 - \ u 0 4 A 6 ] | [ \ u 0 4 A 8 - \ u 0 4 A 8 ] | [ \ u 0 4 A A - \ u 0 4 A A ] | [ \ u 0 4 A C - \ u 0 4 A C ] | [ \ u 0 4 A E - \ u 0 4 A E ] | [ \ u 0 4 B 0 - \ u 0 4 B 0 ] | [ \ u 0 4 B 2 - \ u 0 4 B 2 ] | [ \ u 0 4 B 4 - \ u 0 4 B 4 ] | [ \ u 0 4 B 6 - \ u 0 4 B 6 ] | [ \ u 0 4 B 8 - \ u 0 4 B 8 ] | [ \ u 0 4 B A - \ u 0 4 B A ] | [ \ u 0 4 B C - \ u 0 4 B C ] | [ \ u 0 4 B E - \ u 0 4 B E ] | [ \ u 0 4 C 1 - \ u 0 4 C 1 ] | [ \ u 0 4 C 3 - \ u 0 4 C 3 ] | [ \ u 0 4 C 7 - \ u 0 4 C 7 ] | [ \ u 0 4 C B - \ u 0 4 C B ] | [ \ u 0 4 D 0 - \ u 0 4 D 0 ] | [ \ u 0 4 D 2 - \ u 0 4 D 2 ] | [ \ u 0 4 D 4 - \ u 0 4 D 4 ] | [ \ u 0 4 D 6 - \ u 0 4 D 6 ] | [ \ u 0 4 D 8 - \ u 0 4 D 8 ] | [ \ u 0 4 D A - \ u 0 4 D A ] | [ \ u 0 4 D C - \ u 0 4 D C ] | [ \ u 0 4 D E - \ u 0 4 D E ] | [ \ u 0 4 E 0 - \ u 0 4 E 0 ] | [ \ u 0 4 E 2 - \ u 0 4 E 2 ] | [ \ u 0 4 E 4 - \ u 0 4 E 4 ] | [ \ u 0 4 E 6 - \ u 0 4 E 6 ] | [ \ u 0 4 E 8 - \ u 0 4 E 8 ] | [ \ u 0 4 E A - \ u 0 4 E A ] | [ \ u 0 4 E E - \ u 0 4 E E ] | [ \ u 0 4 F 0 - \ u 0 4 F 0 ] | [ \ u 0 4 F 2 - \ u 0 4 F 2 ] | [ \ u 0 4 F 4 - \ u 0 4 F 4 ] | [ \ u 0 4 F 8 - \ u 0 4 F 8 ] | [ \ u 0 5 3 1 - \ u 0 5 5 6 ] | [ \ u 1 0 A 0 - \ u 1 0 C 5 ] | [ \ u 1 E 0 0 - \ u 1 E 0 0 ] | [ \ u 1 E 0 2 - \ u 1 E 0 2 ] | [ \ u 1 E 0 4 - \ u 1 E 0 4 ] | [ \ u 1 E 0 6 - \ u 1 E 0 6 ] | [ \ u 1 E 0 8 - \ u 1 E 0 8 ] | [ \ u 1 E 0 A - \ u 1 E 0 A ] | [ \ u 1 E 0 C - \ u 1 E 0 C ] | [ \ u 1 E 0 E - \ u 1 E 0 E ] | [ \ u 1 E 1 0 - \ u 1 E 1 0 ] | [ \ u 1 E 1 2 - \ u 1 E 1 2 ] | [ \ u 1 E 1 4 - \ u 1 E 1 4 ] | [ \ u 1 E 1 6 - \ u 1 E 1 6 ] | [ \ u 1 E 1 8 - \ u 1 E 1 8 ] | [ \ u 1 E 1 A - \ u 1 E 1 A ] | [ \ u 1 E 1 C - \ u 1 E 1 C ] | [ \ u 1 E 1 E - \ u 1 E 1 E ] | [ \ u 1 E 2 0 - \ u 1 E 2 0 ] | [ \ u 1 E 2 2 - \ u 1 E 2 2 ] | [ \ u 1 E 2 4 - \ u 1 E 2 4 ] | [ \ u 1 E 2 6 - \ u 1 E 2 6 ] | [ \ u 1 E 2 8 - \ u 1 E 2 8 ] | [ \ u 1 E 2 A - \ u 1 E 2 A ] | [ \ u 1 E 2 C - \ u 1 E 2 C ] | [ \ u 1 E 2 E - \ u 1 E 2 E ] | [ \ u 1 E 3 0 - \ u 1 E 3 0 ] | [ \ u 1 E 3 2 - \ u 1 E 3 2 ] | [ \ u 1 E 3 4 - \ u 1 E 3 4 ] | [ \ u 1 E 3 6 - \ u 1 E 3 6 ] | [ \ u 1 E 3 8 - \ u 1 E 3 8 ] | [ \ u 1 E 3 A - \ u 1 E 3 A ] | [ \ u 1 E 3 C - \ u 1 E 3 C ] | [ \ u 1 E 3 E - \ u 1 E 3 E ] | [ \ u 1 E 4 0 - \ u 1 E 4 0 ] | [ \ u 1 E 4 2 - \ u 1 E 4 2 ] | [ \ u 1 E 4 4 - \ u 1 E 4 4 ] | [ \ u 1 E 4 6 - \ u 1 E 4 6 ] | [ \ u 1 E 4 8 - \ u 1 E 4 8 ] | [ \ u 1 E 4 A - \ u 1 E 4 A ] | [ \ u 1 E 4 C - \ u 1 E 4 C ] | [ \ u 1 E 4 E - \ u 1 E 4 E ] | [ \ u 1 E 5 0 - \ u 1 E 5 0 ] | [ \ u 1 E 5 2 - \ u 1 E 5 2 ] | [ \ u 1 E 5 4 - \ u 1 E 5 4 ] | [ \ u 1 E 5 6 - \ u 1 E 5 6 ] | [ \ u 1 E 5 8 - \ u 1 E 5 8 ] | [ \ u 1 E 5 A - \ u 1 E 5 A ] | [ \ u 1 E 5 C - \ u 1 E 5 C ] | [ \ u 1 E 5 E - \ u 1 E 5 E ] | [ \ u 1 E 6 0 -
Ll : / [ \ u 0 0 6 1 - \ u 0 0 7 A ] | [ \ u 0 0 A A - \ u 0 0 A A ] | [ \ u 0 0 B 5 - \ u 0 0 B 5 ] | [ \ u 0 0 B A - \ u 0 0 B A ] | [ \ u 0 0 D F - \ u 0 0 F 6 ] | [ \ u 0 0 F 8 - \ u 0 0 F F ] | [ \ u 0 1 0 1 - \ u 0 1 0 1 ] | [ \ u 0 1 0 3 - \ u 0 1 0 3 ] | [ \ u 0 1 0 5 - \ u 0 1 0 5 ] | [ \ u 0 1 0 7 - \ u 0 1 0 7 ] | [ \ u 0 1 0 9 - \ u 0 1 0 9 ] | [ \ u 0 1 0 B - \ u 0 1 0 B ] | [ \ u 0 1 0 D - \ u 0 1 0 D ] | [ \ u 0 1 0 F - \ u 0 1 0 F ] | [ \ u 0 1 1 1 - \ u 0 1 1 1 ] | [ \ u 0 1 1 3 - \ u 0 1 1 3 ] | [ \ u 0 1 1 5 - \ u 0 1 1 5 ] | [ \ u 0 1 1 7 - \ u 0 1 1 7 ] | [ \ u 0 1 1 9 - \ u 0 1 1 9 ] | [ \ u 0 1 1 B - \ u 0 1 1 B ] | [ \ u 0 1 1 D - \ u 0 1 1 D ] | [ \ u 0 1 1 F - \ u 0 1 1 F ] | [ \ u 0 1 2 1 - \ u 0 1 2 1 ] | [ \ u 0 1 2 3 - \ u 0 1 2 3 ] | [ \ u 0 1 2 5 - \ u 0 1 2 5 ] | [ \ u 0 1 2 7 - \ u 0 1 2 7 ] | [ \ u 0 1 2 9 - \ u 0 1 2 9 ] | [ \ u 0 1 2 B - \ u 0 1 2 B ] | [ \ u 0 1 2 D - \ u 0 1 2 D ] | [ \ u 0 1 2 F - \ u 0 1 2 F ] | [ \ u 0 1 3 1 - \ u 0 1 3 1 ] | [ \ u 0 1 3 3 - \ u 0 1 3 3 ] | [ \ u 0 1 3 5 - \ u 0 1 3 5 ] | [ \ u 0 1 3 7 - \ u 0 1 3 8 ] | [ \ u 0 1 3 A - \ u 0 1 3 A ] | [ \ u 0 1 3 C - \ u 0 1 3 C ] | [ \ u 0 1 3 E - \ u 0 1 3 E ] | [ \ u 0 1 4 0 - \ u 0 1 4 0 ] | [ \ u 0 1 4 2 - \ u 0 1 4 2 ] | [ \ u 0 1 4 4 - \ u 0 1 4 4 ] | [ \ u 0 1 4 6 - \ u 0 1 4 6 ] | [ \ u 0 1 4 8 - \ u 0 1 4 9 ] | [ \ u 0 1 4 B - \ u 0 1 4 B ] | [ \ u 0 1 4 D - \ u 0 1 4 D ] | [ \ u 0 1 4 F - \ u 0 1 4 F ] | [ \ u 0 1 5 1 - \ u 0 1 5 1 ] | [ \ u 0 1 5 3 - \ u 0 1 5 3 ] | [ \ u 0 1 5 5 - \ u 0 1 5 5 ] | [ \ u 0 1 5 7 - \ u 0 1 5 7 ] | [ \ u 0 1 5 9 - \ u 0 1 5 9 ] | [ \ u 0 1 5 B - \ u 0 1 5 B ] | [ \ u 0 1 5 D - \ u 0 1 5 D ] | [ \ u 0 1 5 F - \ u 0 1 5 F ] | [ \ u 0 1 6 1 - \ u 0 1 6 1 ] | [ \ u 0 1 6 3 - \ u 0 1 6 3 ] | [ \ u 0 1 6 5 - \ u 0 1 6 5 ] | [ \ u 0 1 6 7 - \ u 0 1 6 7 ] | [ \ u 0 1 6 9 - \ u 0 1 6 9 ] | [ \ u 0 1 6 B - \ u 0 1 6 B ] | [ \ u 0 1 6 D - \ u 0 1 6 D ] | [ \ u 0 1 6 F - \ u 0 1 6 F ] | [ \ u 0 1 7 1 - \ u 0 1 7 1 ] | [ \ u 0 1 7 3 - \ u 0 1 7 3 ] | [ \ u 0 1 7 5 - \ u 0 1 7 5 ] | [ \ u 0 1 7 7 - \ u 0 1 7 7 ] | [ \ u 0 1 7 A - \ u 0 1 7 A ] | [ \ u 0 1 7 C - \ u 0 1 7 C ] | [ \ u 0 1 7 E - \ u 0 1 8 0 ] | [ \ u 0 1 8 3 - \ u 0 1 8 3 ] | [ \ u 0 1 8 5 - \ u 0 1 8 5 ] | [ \ u 0 1 8 8 - \ u 0 1 8 8 ] | [ \ u 0 1 8 C - \ u 0 1 8 D ] | [ \ u 0 1 9 2 - \ u 0 1 9 2 ] | [ \ u 0 1 9 5 - \ u 0 1 9 5 ] | [ \ u 0 1 9 9 - \ u 0 1 9 B ] | [ \ u 0 1 9 E - \ u 0 1 9 E ] | [ \ u 0 1 A 1 - \ u 0 1 A 1 ] | [ \ u 0 1 A 3 - \ u 0 1 A 3 ] | [ \ u 0 1 A 5 - \ u 0 1 A 5 ] | [ \ u 0 1 A 8 - \ u 0 1 A 8 ] | [ \ u 0 1 A B - \ u 0 1 A B ] | [ \ u 0 1 A D - \ u 0 1 A D ] | [ \ u 0 1 B 0 - \ u 0 1 B 0 ] | [ \ u 0 1 B 4 - \ u 0 1 B 4 ] | [ \ u 0 1 B 6 - \ u 0 1 B 6 ] | [ \ u 0 1 B 9 - \ u 0 1 B A ] | [ \ u 0 1 B D - \ u 0 1 B D ] | [ \ u 0 1 C 6 - \ u 0 1 C 6 ] | [ \ u 0 1 C 9 - \ u 0 1 C 9 ] | [ \ u 0 1 C C - \ u 0 1 C C ] | [ \ u 0 1 C E - \ u 0 1 C E ] | [ \ u 0 1 D 0 - \ u 0 1 D 0 ] | [ \ u 0 1 D 2 - \ u 0 1 D 2 ] | [ \ u 0 1 D 4 - \ u 0 1 D 4 ] | [ \ u 0 1 D 6 - \ u 0 1 D 6 ] | [ \ u 0 1 D 8 - \ u 0 1 D 8 ] | [ \ u 0 1 D A - \ u 0 1 D A ] | [ \ u 0 1 D C - \ u 0 1 D D ] | [ \ u 0 1 D F - \ u 0 1 D F ] | [ \ u 0 1 E 1 - \ u 0 1 E 1 ] | [ \ u 0 1 E 3 - \ u 0 1 E 3 ] | [ \ u 0 1 E 5 - \ u 0 1 E 5 ] | [ \ u 0 1 E 7 - \ u 0 1 E 7 ] | [ \ u 0 1 E 9 - \ u 0 1 E 9 ] | [ \ u 0 1 E B - \ u 0 1 E B ] | [ \ u 0 1 E D - \ u 0 1 E D ] | [ \ u 0 1 E F - \ u 0 1 F 0 ] | [ \ u 0 1 F 3 - \ u 0 1 F 3 ] | [ \ u 0 1 F 5 - \ u 0 1 F 5 ] | [ \ u 0 1 F B - \ u 0 1 F B ] | [ \ u 0 1 F D - \ u 0 1 F D ] | [ \ u 0 1 F F - \ u 0 1 F F ] | [ \ u 0 2 0 1 - \ u 0 2 0 1 ] | [ \ u 0 2 0 3 - \ u 0 2 0 3 ] | [ \ u 0 2 0 5 - \ u 0 2 0 5 ] | [ \ u 0 2 0 7 - \ u 0 2 0 7 ] | [ \ u 0 2 0 9 - \ u 0 2 0 9 ] | [ \ u 0 2 0 B - \ u 0 2 0 B ] | [ \ u 0 2 0 D - \ u 0 2 0 D ] | [ \ u 0 2 0 F - \ u 0 2 0 F ] | [ \ u 0 2 1 1 - \ u 0 2 1 1 ] | [ \ u 0 2 1 3 - \ u 0 2 1 3 ] | [ \ u 0 2 1 5 - \ u 0 2 1 5 ] | [ \ u 0 2 1 7 - \ u 0 2 1 7 ] | [ \ u 0 2 5 0 - \ u 0 2 A 8 ] | [ \ u 0 3 9 0 - \ u 0 3 9 0 ] | [ \ u 0 3 A C - \ u 0 3 C E ] | [ \ u 0 3 D 0 - \ u 0 3 D 1 ] | [ \ u 0 3 D 5 - \ u 0 3 D 6 ] | [ \ u 0 3 E 3 - \ u 0 3 E 3 ] | [ \ u 0 3 E 5 - \ u 0 3 E 5 ] | [ \ u 0 3 E 7 - \ u 0 3 E 7 ] | [ \ u 0 3 E 9 - \ u 0 3 E 9 ] | [ \ u 0 3 E B - \ u 0 3 E B ] | [ \ u 0 3 E D - \ u 0 3 E D ] | [ \ u 0 3 E F - \ u 0 3 F 2 ] | [ \ u 0 4 3 0 - \ u 0 4 4 F ] | [ \ u 0 4 5 1 - \ u 0 4 5 C ] | [ \ u 0 4 5 E - \ u 0 4 5 F ] | [ \ u 0 4 6 1 - \ u 0 4 6 1 ] | [ \ u 0 4 6 3 - \ u 0 4 6 3 ] | [ \ u 0 4 6 5 - \ u 0 4 6 5 ] | [ \ u 0 4 6 7 - \ u 0 4 6 7 ] | [ \ u 0 4 6 9 - \ u 0 4 6 9 ] | [ \ u 0 4 6 B - \ u 0 4 6 B ] | [ \ u 0 4 6 D - \ u 0 4 6 D ] | [ \ u 0 4 6 F - \ u 0 4 6 F ] | [ \ u 0 4 7 1 - \ u 0 4 7 1 ] | [ \ u 0 4 7 3 - \ u 0 4 7 3 ] | [ \ u 0 4 7 5 - \ u 0 4 7 5 ] | [ \ u 0 4 7 7 - \ u 0 4 7 7 ] | [ \ u 0 4 7 9 - \ u 0 4 7 9 ] | [ \ u 0 4 7 B - \ u 0 4 7 B ] | [ \ u 0 4 7 D - \ u 0 4 7 D ] | [ \ u 0 4 7 F - \ u 0 4 7 F ] | [ \ u 0 4 8 1 - \ u 0 4 8 1 ] | [ \ u 0 4 9 1 - \ u 0 4 9 1 ] | [ \ u 0 4 9 3 - \ u 0 4 9 3 ] | [ \ u 0 4 9 5 - \ u 0 4 9 5 ] | [ \ u 0 4 9 7 - \ u 0 4 9 7 ] | [ \ u 0 4 9 9 - \ u 0 4 9 9 ] | [ \ u 0 4 9 B - \ u 0 4 9 B ] | [ \ u 0 4 9 D - \ u 0 4 9 D ] | [ \ u 0 4 9 F - \ u 0 4 9 F ] | [ \ u 0 4 A 1 - \ u 0 4 A 1 ] | [ \ u 0 4 A 3 - \ u 0 4 A 3 ] | [ \ u 0 4 A 5 - \ u 0 4 A 5 ] | [ \ u 0 4 A 7 - \ u 0 4 A 7 ] | [ \ u 0 4 A 9 - \ u 0 4 A 9 ] | [ \ u 0 4 A B - \ u 0 4 A B ] | [ \ u 0 4 A D - \ u 0 4 A D ] | [ \ u 0 4 A F - \ u 0 4 A F ] | [ \ u 0 4 B 1 - \ u 0 4 B 1 ] | [ \ u 0 4 B 3 - \ u 0 4 B 3 ] | [ \ u 0 4 B 5 - \ u 0 4 B 5 ] | [ \ u 0 4 B 7 - \ u 0 4 B 7 ] | [ \ u 0 4 B 9 - \ u 0 4 B 9 ] | [ \ u 0 4 B B - \ u 0 4 B B ] | [ \ u 0 4 B D - \ u 0 4 B D ] | [ \ u 0 4 B F - \ u 0 4 B F ] | [ \ u 0 4 C 2 - \ u 0 4 C 2 ] | [ \ u 0 4 C 4 - \ u 0 4 C 4 ] | [ \ u 0 4 C 8 - \ u 0 4 C 8 ] | [ \ u 0 4 C C - \ u 0 4 C C ] | [ \ u 0 4 D 1 - \ u 0 4 D 1 ] | [ \ u 0 4 D 3 - \ u 0 4 D 3 ] | [ \ u 0 4 D 5 - \ u 0 4 D 5 ] | [ \ u 0 4 D 7 - \ u 0 4 D 7 ] | [ \ u 0 4 D 9 - \ u 0 4 D 9 ] | [ \ u 0 4 D B - \ u 0 4 D B ] | [ \ u 0 4 D D - \ u 0 4 D D ] | [ \ u 0 4 D F - \ u 0 4 D F ] | [ \ u 0 4 E 1 - \ u 0 4 E 1 ] | [ \ u 0 4 E 3 - \ u 0 4 E 3 ] | [ \ u 0 4 E 5 - \ u 0 4 E 5 ] | [ \ u 0 4 E 7 - \ u 0 4 E 7 ] | [ \ u 0 4 E 9 - \ u 0 4 E 9 ] | [ \ u 0 4 E B - \ u 0 4 E B ] | [ \ u 0 4 E F - \ u 0 4 E F ] | [ \ u 0 4 F 1 - \ u 0 4 F 1 ] | [ \ u 0 4 F 3 - \ u 0 4 F 3 ] | [ \ u 0 4 F 5 - \ u 0 4 F 5 ] | [ \ u 0 4 F 9 - \ u 0 4 F 9 ] | [ \ u 0 5 6 1 - \ u 0 5 8 7 ] | [ \ u 1 0 D 0 - \ u 1 0 F 6 ] | [ \ u 1 E 0 1 - \ u 1 E 0 1 ] | [ \ u 1 E 0 3 - \ u 1 E 0 3 ] | [ \ u 1 E 0 5 - \ u 1 E 0 5 ] | [ \ u 1 E 0 7 - \ u 1 E 0 7 ] | [ \ u 1 E 0 9 - \ u 1 E 0 9 ] | [ \ u 1 E 0 B - \ u 1 E 0 B ] | [ \ u 1 E 0 D - \ u 1 E 0 D ] | [ \ u 1 E 0 F - \ u 1 E 0 F ] | [ \ u 1 E 1 1 - \ u 1 E 1 1 ] | [ \ u 1 E 1 3 - \ u 1 E 1 3 ] | [ \ u 1 E 1 5 - \ u 1 E 1 5 ] | [ \ u 1 E 1 7 - \ u 1 E 1 7 ] | [ \ u 1 E 1 9 - \ u 1 E 1 9 ] | [ \ u 1 E 1 B - \ u 1 E 1 B ] | [ \ u 1 E 1 D - \ u 1 E 1 D ] | [ \ u 1 E 1 F - \ u 1 E 1 F ] | [ \ u 1 E 2 1 - \ u 1 E 2 1 ] | [ \ u 1 E 2 3 - \ u 1 E 2 3 ] | [ \ u 1 E 2 5 - \ u 1 E 2 5 ] | [ \ u 1 E 2 7 - \ u 1 E 2 7 ] | [ \ u 1 E 2 9 - \ u 1 E 2 9 ] | [ \ u 1 E 2 B - \ u 1 E 2 B ] | [ \ u 1 E 2 D - \ u 1 E 2 D ] | [ \ u 1 E 2 F - \ u 1 E 2 F ] | [ \ u 1 E 3 1 - \ u 1 E 3 1 ] | [ \ u 1 E 3 3 - \ u 1 E 3 3 ] | [ \ u 1 E 3 5 - \ u 1 E 3 5 ] | [ \ u 1 E 3 7 - \ u 1 E 3 7 ] | [ \ u 1 E 3 9 - \ u 1 E 3 9 ] | [ \ u 1 E 3 B - \ u 1 E 3 B ] | [ \ u 1 E 3 D - \ u 1 E 3 D ] | [ \ u 1 E 3 F - \ u 1 E 3 F ] | [ \ u 1 E 4 1 - \ u 1 E 4 1 ] | [ \ u 1 E 4 3 - \ u 1 E 4 3 ] | [ \ u 1 E 4 5 - \ u 1 E 4 5 ] | [ \ u 1 E 4 7 - \ u 1 E 4 7 ] | [ \ u 1 E 4 9 - \ u 1 E 4 9 ] | [ \ u 1 E 4 B - \ u 1 E 4 B ] | [ \ u 1 E 4 D - \ u 1 E 4 D ] | [ \ u 1 E 4 F - \ u 1 E 4 F ] | [ \ u 1 E 5 1 - \ u 1 E 5 1 ] | [ \ u 1 E 5 3 - \ u 1 E 5 3 ] | [ \ u 1 E 5 5 - \ u 1 E 5 5 ] | [ \ u 1 E 5 7 - \ u 1 E 5 7 ] | [ \ u 1 E 5 9 - \ u 1 E 5 9 ] | [ \ u 1 E 5 B - \ u 1 E 5 B ] | [ \ u 1 E 5 D - \ u 1 E 5 D ] | [ \ u 1 E 5 F - \ u 1 E 5 F ] | [ \ u 1 E 6 1 - \ u 1 E 6 1 ] | [ \ u 1 E 6 3 - \ u 1 E 6 3 ] | [ \ u 1 E 6 5 -
Lt : /[\u01C5-\u01C5]|[\u01C8-\u01C8]|[\u01CB-\u01CB]|[\u01F2-\u01F2]/ ,
Lm : /[\u02B0-\u02B8]|[\u02BB-\u02C1]|[\u02D0-\u02D1]|[\u02E0-\u02E4]|[\u037A-\u037A]|[\u0559-\u0559]|[\u0640-\u0640]|[\u06E5-\u06E6]|[\u0E46-\u0E46]|[\u0EC6-\u0EC6]|[\u3005-\u3005]|[\u3031-\u3035]|[\u309D-\u309E]|[\u30FC-\u30FE]|[\uFF70-\uFF70]|[\uFF9E-\uFF9F]/ ,
Lo : /[\u01AA-\u01AA]|[\u01BB-\u01BB]|[\u01BE-\u01C3]|[\u03F3-\u03F3]|[\u04C0-\u04C0]|[\u05D0-\u05EA]|[\u05F0-\u05F2]|[\u0621-\u063A]|[\u0641-\u064A]|[\u0671-\u06B7]|[\u06BA-\u06BE]|[\u06C0-\u06CE]|[\u06D0-\u06D3]|[\u06D5-\u06D5]|[\u0905-\u0939]|[\u093D-\u093D]|[\u0950-\u0950]|[\u0958-\u0961]|[\u0985-\u098C]|[\u098F-\u0990]|[\u0993-\u09A8]|[\u09AA-\u09B0]|[\u09B2-\u09B2]|[\u09B6-\u09B9]|[\u09DC-\u09DD]|[\u09DF-\u09E1]|[\u09F0-\u09F1]|[\u0A05-\u0A0A]|[\u0A0F-\u0A10]|[\u0A13-\u0A28]|[\u0A2A-\u0A30]|[\u0A32-\u0A33]|[\u0A35-\u0A36]|[\u0A38-\u0A39]|[\u0A59-\u0A5C]|[\u0A5E-\u0A5E]|[\u0A72-\u0A74]|[\u0A85-\u0A8B]|[\u0A8D-\u0A8D]|[\u0A8F-\u0A91]|[\u0A93-\u0AA8]|[\u0AAA-\u0AB0]|[\u0AB2-\u0AB3]|[\u0AB5-\u0AB9]|[\u0ABD-\u0ABD]|[\u0AD0-\u0AD0]|[\u0AE0-\u0AE0]|[\u0B05-\u0B0C]|[\u0B0F-\u0B10]|[\u0B13-\u0B28]|[\u0B2A-\u0B30]|[\u0B32-\u0B33]|[\u0B36-\u0B39]|[\u0B3D-\u0B3D]|[\u0B5C-\u0B5D]|[\u0B5F-\u0B61]|[\u0B85-\u0B8A]|[\u0B8E-\u0B90]|[\u0B92-\u0B95]|[\u0B99-\u0B9A]|[\u0B9C-\u0B9C]|[\u0B9E-\u0B9F]|[\u0BA3-\u0BA4]|[\u0BA8-\u0BAA]|[\u0BAE-\u0BB5]|[\u0BB7-\u0BB9]|[\u0C05-\u0C0C]|[\u0C0E-\u0C10]|[\u0C12-\u0C28]|[\u0C2A-\u0C33]|[\u0C35-\u0C39]|[\u0C60-\u0C61]|[\u0C85-\u0C8C]|[\u0C8E-\u0C90]|[\u0C92-\u0CA8]|[\u0CAA-\u0CB3]|[\u0CB5-\u0CB9]|[\u0CDE-\u0CDE]|[\u0CE0-\u0CE1]|[\u0D05-\u0D0C]|[\u0D0E-\u0D10]|[\u0D12-\u0D28]|[\u0D2A-\u0D39]|[\u0D60-\u0D61]|[\u0E01-\u0E30]|[\u0E32-\u0E33]|[\u0E40-\u0E45]|[\u0E81-\u0E82]|[\u0E84-\u0E84]|[\u0E87-\u0E88]|[\u0E8A-\u0E8A]|[\u0E8D-\u0E8D]|[\u0E94-\u0E97]|[\u0E99-\u0E9F]|[\u0EA1-\u0EA3]|[\u0EA5-\u0EA5]|[\u0EA7-\u0EA7]|[\u0EAA-\u0EAB]|[\u0EAD-\u0EB0]|[\u0EB2-\u0EB3]|[\u0EBD-\u0EBD]|[\u0EC0-\u0EC4]|[\u0EDC-\u0EDD]|[\u0F00-\u0F00]|[\u0F40-\u0F47]|[\u0F49-\u0F69]|[\u0F88-\u0F8B]|[\u1100-\u1159]|[\u115F-\u11A2]|[\u11A8-\u11F9]|[\u2135-\u2138]|[\u3006-\u3006]|[\u3041-\u3094]|[\u30A1-\u30FA]|[\u3105-\u312C]|[\u3131-\u318E]|[\u4E00-\u9FA5]|[\uAC00-\uD7A3]|[\uF900-\uFA2D]|[\uFB1F-\uFB28]|[\uFB2A-\uFB36]|[\uFB38-\uFB3C]|[\uFB3E-\uFB3E]|[\uFB40-\uFB41]|[\uFB43-\uFB44]|[\uFB46-\uFBB1]|[\uFBD3-\uFD3D]|[\uFD50-\uFD8F]|[\uFD92-\uFDC7]|[\uFDF0-\uFDFB]|[\uFE70-\uFE72]|[\uFE74-\uFE74]|[\uFE76-\uFEFC]|[\uFF66-\uFF6F]|[\uFF71-\uFF9D]|[\uFFA0-\uFFBE]|[\uFFC2-\uFFC7]|[\uFFCA-\uFFCF]|[\uFFD2-\uFFD7]|[\uFFDA-\uFFDC]/ ,
// Numbers
Nl : /[\u2160-\u2182]|[\u3007-\u3007]|[\u3021-\u3029]/ ,
Nd : /[\u0030-\u0039]|[\u0660-\u0669]|[\u06F0-\u06F9]|[\u0966-\u096F]|[\u09E6-\u09EF]|[\u0A66-\u0A6F]|[\u0AE6-\u0AEF]|[\u0B66-\u0B6F]|[\u0BE7-\u0BEF]|[\u0C66-\u0C6F]|[\u0CE6-\u0CEF]|[\u0D66-\u0D6F]|[\u0E50-\u0E59]|[\u0ED0-\u0ED9]|[\u0F20-\u0F29]|[\uFF10-\uFF19]/ ,
// Marks
Mn : /[\u0300-\u0345]|[\u0360-\u0361]|[\u0483-\u0486]|[\u0591-\u05A1]|[\u05A3-\u05B9]|[\u05BB-\u05BD]|[\u05BF-\u05BF]|[\u05C1-\u05C2]|[\u05C4-\u05C4]|[\u064B-\u0652]|[\u0670-\u0670]|[\u06D6-\u06DC]|[\u06DF-\u06E4]|[\u06E7-\u06E8]|[\u06EA-\u06ED]|[\u0901-\u0902]|[\u093C-\u093C]|[\u0941-\u0948]|[\u094D-\u094D]|[\u0951-\u0954]|[\u0962-\u0963]|[\u0981-\u0981]|[\u09BC-\u09BC]|[\u09C1-\u09C4]|[\u09CD-\u09CD]|[\u09E2-\u09E3]|[\u0A02-\u0A02]|[\u0A3C-\u0A3C]|[\u0A41-\u0A42]|[\u0A47-\u0A48]|[\u0A4B-\u0A4D]|[\u0A70-\u0A71]|[\u0A81-\u0A82]|[\u0ABC-\u0ABC]|[\u0AC1-\u0AC5]|[\u0AC7-\u0AC8]|[\u0ACD-\u0ACD]|[\u0B01-\u0B01]|[\u0B3C-\u0B3C]|[\u0B3F-\u0B3F]|[\u0B41-\u0B43]|[\u0B4D-\u0B4D]|[\u0B56-\u0B56]|[\u0B82-\u0B82]|[\u0BC0-\u0BC0]|[\u0BCD-\u0BCD]|[\u0C3E-\u0C40]|[\u0C46-\u0C48]|[\u0C4A-\u0C4D]|[\u0C55-\u0C56]|[\u0CBF-\u0CBF]|[\u0CC6-\u0CC6]|[\u0CCC-\u0CCD]|[\u0D41-\u0D43]|[\u0D4D-\u0D4D]|[\u0E31-\u0E31]|[\u0E34-\u0E3A]|[\u0E47-\u0E4E]|[\u0EB1-\u0EB1]|[\u0EB4-\u0EB9]|[\u0EBB-\u0EBC]|[\u0EC8-\u0ECD]|[\u0F18-\u0F19]|[\u0F35-\u0F35]|[\u0F37-\u0F37]|[\u0F39-\u0F39]|[\u0F71-\u0F7E]|[\u0F80-\u0F84]|[\u0F86-\u0F87]|[\u0F90-\u0F95]|[\u0F97-\u0F97]|[\u0F99-\u0FAD]|[\u0FB1-\u0FB7]|[\u0FB9-\u0FB9]|[\u20D0-\u20DC]|[\u20E1-\u20E1]|[\u302A-\u302F]|[\u3099-\u309A]|[\uFB1E-\uFB1E]|[\uFE20-\uFE23]/ ,
Mc : /[\u0903-\u0903]|[\u093E-\u0940]|[\u0949-\u094C]|[\u0982-\u0983]|[\u09BE-\u09C0]|[\u09C7-\u09C8]|[\u09CB-\u09CC]|[\u09D7-\u09D7]|[\u0A3E-\u0A40]|[\u0A83-\u0A83]|[\u0ABE-\u0AC0]|[\u0AC9-\u0AC9]|[\u0ACB-\u0ACC]|[\u0B02-\u0B03]|[\u0B3E-\u0B3E]|[\u0B40-\u0B40]|[\u0B47-\u0B48]|[\u0B4B-\u0B4C]|[\u0B57-\u0B57]|[\u0B83-\u0B83]|[\u0BBE-\u0BBF]|[\u0BC1-\u0BC2]|[\u0BC6-\u0BC8]|[\u0BCA-\u0BCC]|[\u0BD7-\u0BD7]|[\u0C01-\u0C03]|[\u0C41-\u0C44]|[\u0C82-\u0C83]|[\u0CBE-\u0CBE]|[\u0CC0-\u0CC4]|[\u0CC7-\u0CC8]|[\u0CCA-\u0CCB]|[\u0CD5-\u0CD6]|[\u0D02-\u0D03]|[\u0D3E-\u0D40]|[\u0D46-\u0D48]|[\u0D4A-\u0D4C]|[\u0D57-\u0D57]|[\u0F3E-\u0F3F]|[\u0F7F-\u0F7F]/ ,
// Punctuation, Connector
Pc : /[\u005F-\u005F]|[\u203F-\u2040]|[\u30FB-\u30FB]|[\uFE33-\uFE34]|[\uFE4D-\uFE4F]|[\uFF3F-\uFF3F]|[\uFF65-\uFF65]/ ,
// Separator, Space
Zs : /[\u2000-\u200B]|[\u3000-\u3000]/ ,
// These two are not real Unicode categories, but our useful for Ohm.
// L is a combination of all the letter categories.
// Ltmo is a combination of Lt, Lm, and Lo.
L : / [ \ u 0 0 4 1 - \ u 0 0 5 A ] | [ \ u 0 0 C 0 - \ u 0 0 D 6 ] | [ \ u 0 0 D 8 - \ u 0 0 D E ] | [ \ u 0 1 0 0 - \ u 0 1 0 0 ] | [ \ u 0 1 0 2 - \ u 0 1 0 2 ] | [ \ u 0 1 0 4 - \ u 0 1 0 4 ] | [ \ u 0 1 0 6 - \ u 0 1 0 6 ] | [ \ u 0 1 0 8 - \ u 0 1 0 8 ] | [ \ u 0 1 0 A - \ u 0 1 0 A ] | [ \ u 0 1 0 C - \ u 0 1 0 C ] | [ \ u 0 1 0 E - \ u 0 1 0 E ] | [ \ u 0 1 1 0 - \ u 0 1 1 0 ] | [ \ u 0 1 1 2 - \ u 0 1 1 2 ] | [ \ u 0 1 1 4 - \ u 0 1 1 4 ] | [ \ u 0 1 1 6 - \ u 0 1 1 6 ] | [ \ u 0 1 1 8 - \ u 0 1 1 8 ] | [ \ u 0 1 1 A - \ u 0 1 1 A ] | [ \ u 0 1 1 C - \ u 0 1 1 C ] | [ \ u 0 1 1 E - \ u 0 1 1 E ] | [ \ u 0 1 2 0 - \ u 0 1 2 0 ] | [ \ u 0 1 2 2 - \ u 0 1 2 2 ] | [ \ u 0 1 2 4 - \ u 0 1 2 4 ] | [ \ u 0 1 2 6 - \ u 0 1 2 6 ] | [ \ u 0 1 2 8 - \ u 0 1 2 8 ] | [ \ u 0 1 2 A - \ u 0 1 2 A ] | [ \ u 0 1 2 C - \ u 0 1 2 C ] | [ \ u 0 1 2 E - \ u 0 1 2 E ] | [ \ u 0 1 3 0 - \ u 0 1 3 0 ] | [ \ u 0 1 3 2 - \ u 0 1 3 2 ] | [ \ u 0 1 3 4 - \ u 0 1 3 4 ] | [ \ u 0 1 3 6 - \ u 0 1 3 6 ] | [ \ u 0 1 3 9 - \ u 0 1 3 9 ] | [ \ u 0 1 3 B - \ u 0 1 3 B ] | [ \ u 0 1 3 D - \ u 0 1 3 D ] | [ \ u 0 1 3 F - \ u 0 1 3 F ] | [ \ u 0 1 4 1 - \ u 0 1 4 1 ] | [ \ u 0 1 4 3 - \ u 0 1 4 3 ] | [ \ u 0 1 4 5 - \ u 0 1 4 5 ] | [ \ u 0 1 4 7 - \ u 0 1 4 7 ] | [ \ u 0 1 4 A - \ u 0 1 4 A ] | [ \ u 0 1 4 C - \ u 0 1 4 C ] | [ \ u 0 1 4 E - \ u 0 1 4 E ] | [ \ u 0 1 5 0 - \ u 0 1 5 0 ] | [ \ u 0 1 5 2 - \ u 0 1 5 2 ] | [ \ u 0 1 5 4 - \ u 0 1 5 4 ] | [ \ u 0 1 5 6 - \ u 0 1 5 6 ] | [ \ u 0 1 5 8 - \ u 0 1 5 8 ] | [ \ u 0 1 5 A - \ u 0 1 5 A ] | [ \ u 0 1 5 C - \ u 0 1 5 C ] | [ \ u 0 1 5 E - \ u 0 1 5 E ] | [ \ u 0 1 6 0 - \ u 0 1 6 0 ] | [ \ u 0 1 6 2 - \ u 0 1 6 2 ] | [ \ u 0 1 6 4 - \ u 0 1 6 4 ] | [ \ u 0 1 6 6 - \ u 0 1 6 6 ] | [ \ u 0 1 6 8 - \ u 0 1 6 8 ] | [ \ u 0 1 6 A - \ u 0 1 6 A ] | [ \ u 0 1 6 C - \ u 0 1 6 C ] | [ \ u 0 1 6 E - \ u 0 1 6 E ] | [ \ u 0 1 7 0 - \ u 0 1 7 0 ] | [ \ u 0 1 7 2 - \ u 0 1 7 2 ] | [ \ u 0 1 7 4 - \ u 0 1 7 4 ] | [ \ u 0 1 7 6 - \ u 0 1 7 6 ] | [ \ u 0 1 7 8 - \ u 0 1 7 9 ] | [ \ u 0 1 7 B - \ u 0 1 7 B ] | [ \ u 0 1 7 D - \ u 0 1 7 D ] | [ \ u 0 1 8 1 - \ u 0 1 8 2 ] | [ \ u 0 1 8 4 - \ u 0 1 8 4 ] | [ \ u 0 1 8 6 - \ u 0 1 8 7 ] | [ \ u 0 1 8 9 - \ u 0 1 8 B ] | [ \ u 0 1 8 E - \ u 0 1 9 1 ] | [ \ u 0 1 9 3 - \ u 0 1 9 4 ] | [ \ u 0 1 9 6 - \ u 0 1 9 8 ] | [ \ u 0 1 9 C - \ u 0 1 9 D ] | [ \ u 0 1 9 F - \ u 0 1 A 0 ] | [ \ u 0 1 A 2 - \ u 0 1 A 2 ] | [ \ u 0 1 A 4 - \ u 0 1 A 4 ] | [ \ u 0 1 A 6 - \ u 0 1 A 7 ] | [ \ u 0 1 A 9 - \ u 0 1 A 9 ] | [ \ u 0 1 A C - \ u 0 1 A C ] | [ \ u 0 1 A E - \ u 0 1 A F ] | [ \ u 0 1 B 1 - \ u 0 1 B 3 ] | [ \ u 0 1 B 5 - \ u 0 1 B 5 ] | [ \ u 0 1 B 7 - \ u 0 1 B 8 ] | [ \ u 0 1 B C - \ u 0 1 B C ] | [ \ u 0 1 C 4 - \ u 0 1 C 4 ] | [ \ u 0 1 C 7 - \ u 0 1 C 7 ] | [ \ u 0 1 C A - \ u 0 1 C A ] | [ \ u 0 1 C D - \ u 0 1 C D ] | [ \ u 0 1 C F - \ u 0 1 C F ] | [ \ u 0 1 D 1 - \ u 0 1 D 1 ] | [ \ u 0 1 D 3 - \ u 0 1 D 3 ] | [ \ u 0 1 D 5 - \ u 0 1 D 5 ] | [ \ u 0 1 D 7 - \ u 0 1 D 7 ] | [ \ u 0 1 D 9 - \ u 0 1 D 9 ] | [ \ u 0 1 D B - \ u 0 1 D B ] | [ \ u 0 1 D E - \ u 0 1 D E ] | [ \ u 0 1 E 0 - \ u 0 1 E 0 ] | [ \ u 0 1 E 2 - \ u 0 1 E 2 ] | [ \ u 0 1 E 4 - \ u 0 1 E 4 ] | [ \ u 0 1 E 6 - \ u 0 1 E 6 ] | [ \ u 0 1 E 8 - \ u 0 1 E 8 ] | [ \ u 0 1 E A - \ u 0 1 E A ] | [ \ u 0 1 E C - \ u 0 1 E C ] | [ \ u 0 1 E E - \ u 0 1 E E ] | [ \ u 0 1 F 1 - \ u 0 1 F 1 ] | [ \ u 0 1 F 4 - \ u 0 1 F 4 ] | [ \ u 0 1 F A - \ u 0 1 F A ] | [ \ u 0 1 F C - \ u 0 1 F C ] | [ \ u 0 1 F E - \ u 0 1 F E ] | [ \ u 0 2 0 0 - \ u 0 2 0 0 ] | [ \ u 0 2 0 2 - \ u 0 2 0 2 ] | [ \ u 0 2 0 4 - \ u 0 2 0 4 ] | [ \ u 0 2 0 6 - \ u 0 2 0 6 ] | [ \ u 0 2 0 8 - \ u 0 2 0 8 ] | [ \ u 0 2 0 A - \ u 0 2 0 A ] | [ \ u 0 2 0 C - \ u 0 2 0 C ] | [ \ u 0 2 0 E - \ u 0 2 0 E ] | [ \ u 0 2 1 0 - \ u 0 2 1 0 ] | [ \ u 0 2 1 2 - \ u 0 2 1 2 ] | [ \ u 0 2 1 4 - \ u 0 2 1 4 ] | [ \ u 0 2 1 6 - \ u 0 2 1 6 ] | [ \ u 0 3 8 6 - \ u 0 3 8 6 ] | [ \ u 0 3 8 8 - \ u 0 3 8 A ] | [ \ u 0 3 8 C - \ u 0 3 8 C ] | [ \ u 0 3 8 E - \ u 0 3 8 F ] | [ \ u 0 3 9 1 - \ u 0 3 A 1 ] | [ \ u 0 3 A 3 - \ u 0 3 A B ] | [ \ u 0 3 D 2 - \ u 0 3 D 4 ] | [ \ u 0 3 D A - \ u 0 3 D A ] | [ \ u 0 3 D C - \ u 0 3 D C ] | [ \ u 0 3 D E - \ u 0 3 D E ] | [ \ u 0 3 E 0 - \ u 0 3 E 0 ] | [ \ u 0 3 E 2 - \ u 0 3 E 2 ] | [ \ u 0 3 E 4 - \ u 0 3 E 4 ] | [ \ u 0 3 E 6 - \ u 0 3 E 6 ] | [ \ u 0 3 E 8 - \ u 0 3 E 8 ] | [ \ u 0 3 E A - \ u 0 3 E A ] | [ \ u 0 3 E C - \ u 0 3 E C ] | [ \ u 0 3 E E - \ u 0 3 E E ] | [ \ u 0 4 0 1 - \ u 0 4 0 C ] | [ \ u 0 4 0 E - \ u 0 4 2 F ] | [ \ u 0 4 6 0 - \ u 0 4 6 0 ] | [ \ u 0 4 6 2 - \ u 0 4 6 2 ] | [ \ u 0 4 6 4 - \ u 0 4 6 4 ] | [ \ u 0 4 6 6 - \ u 0 4 6 6 ] | [ \ u 0 4 6 8 - \ u 0 4 6 8 ] | [ \ u 0 4 6 A - \ u 0 4 6 A ] | [ \ u 0 4 6 C - \ u 0 4 6 C ] | [ \ u 0 4 6 E - \ u 0 4 6 E ] | [ \ u 0 4 7 0 - \ u 0 4 7 0 ] | [ \ u 0 4 7 2 - \ u 0 4 7 2 ] | [ \ u 0 4 7 4 - \ u 0 4 7 4 ] | [ \ u 0 4 7 6 - \ u 0 4 7 6 ] | [ \ u 0 4 7 8 - \ u 0 4 7 8 ] | [ \ u 0 4 7 A - \ u 0 4 7 A ] | [ \ u 0 4 7 C - \ u 0 4 7 C ] | [ \ u 0 4 7 E - \ u 0 4 7 E ] | [ \ u 0 4 8 0 - \ u 0 4 8 0 ] | [ \ u 0 4 9 0 - \ u 0 4 9 0 ] | [ \ u 0 4 9 2 - \ u 0 4 9 2 ] | [ \ u 0 4 9 4 - \ u 0 4 9 4 ] | [ \ u 0 4 9 6 - \ u 0 4 9 6 ] | [ \ u 0 4 9 8 - \ u 0 4 9 8 ] | [ \ u 0 4 9 A - \ u 0 4 9 A ] | [ \ u 0 4 9 C - \ u 0 4 9 C ] | [ \ u 0 4 9 E - \ u 0 4 9 E ] | [ \ u 0 4 A 0 - \ u 0 4 A 0 ] | [ \ u 0 4 A 2 - \ u 0 4 A 2 ] | [ \ u 0 4 A 4 - \ u 0 4 A 4 ] | [ \ u 0 4 A 6 - \ u 0 4 A 6 ] | [ \ u 0 4 A 8 - \ u 0 4 A 8 ] | [ \ u 0 4 A A - \ u 0 4 A A ] | [ \ u 0 4 A C - \ u 0 4 A C ] | [ \ u 0 4 A E - \ u 0 4 A E ] | [ \ u 0 4 B 0 - \ u 0 4 B 0 ] | [ \ u 0 4 B 2 - \ u 0 4 B 2 ] | [ \ u 0 4 B 4 - \ u 0 4 B 4 ] | [ \ u 0 4 B 6 - \ u 0 4 B 6 ] | [ \ u 0 4 B 8 - \ u 0 4 B 8 ] | [ \ u 0 4 B A - \ u 0 4 B A ] | [ \ u 0 4 B C - \ u 0 4 B C ] | [ \ u 0 4 B E - \ u 0 4 B E ] | [ \ u 0 4 C 1 - \ u 0 4 C 1 ] | [ \ u 0 4 C 3 - \ u 0 4 C 3 ] | [ \ u 0 4 C 7 - \ u 0 4 C 7 ] | [ \ u 0 4 C B - \ u 0 4 C B ] | [ \ u 0 4 D 0 - \ u 0 4 D 0 ] | [ \ u 0 4 D 2 - \ u 0 4 D 2 ] | [ \ u 0 4 D 4 - \ u 0 4 D 4 ] | [ \ u 0 4 D 6 - \ u 0 4 D 6 ] | [ \ u 0 4 D 8 - \ u 0 4 D 8 ] | [ \ u 0 4 D A - \ u 0 4 D A ] | [ \ u 0 4 D C - \ u 0 4 D C ] | [ \ u 0 4 D E - \ u 0 4 D E ] | [ \ u 0 4 E 0 - \ u 0 4 E 0 ] | [ \ u 0 4 E 2 - \ u 0 4 E 2 ] | [ \ u 0 4 E 4 - \ u 0 4 E 4 ] | [ \ u 0 4 E 6 - \ u 0 4 E 6 ] | [ \ u 0 4 E 8 - \ u 0 4 E 8 ] | [ \ u 0 4 E A - \ u 0 4 E A ] | [ \ u 0 4 E E - \ u 0 4 E E ] | [ \ u 0 4 F 0 - \ u 0 4 F 0 ] | [ \ u 0 4 F 2 - \ u 0 4 F 2 ] | [ \ u 0 4 F 4 - \ u 0 4 F 4 ] | [ \ u 0 4 F 8 - \ u 0 4 F 8 ] | [ \ u 0 5 3 1 - \ u 0 5 5 6 ] | [ \ u 1 0 A 0 - \ u 1 0 C 5 ] | [ \ u 1 E 0 0 - \ u 1 E 0 0 ] | [ \ u 1 E 0 2 - \ u 1 E 0 2 ] | [ \ u 1 E 0 4 - \ u 1 E 0 4 ] | [ \ u 1 E 0 6 - \ u 1 E 0 6 ] | [ \ u 1 E 0 8 - \ u 1 E 0 8 ] | [ \ u 1 E 0 A - \ u 1 E 0 A ] | [ \ u 1 E 0 C - \ u 1 E 0 C ] | [ \ u 1 E 0 E - \ u 1 E 0 E ] | [ \ u 1 E 1 0 - \ u 1 E 1 0 ] | [ \ u 1 E 1 2 - \ u 1 E 1 2 ] | [ \ u 1 E 1 4 - \ u 1 E 1 4 ] | [ \ u 1 E 1 6 - \ u 1 E 1 6 ] | [ \ u 1 E 1 8 - \ u 1 E 1 8 ] | [ \ u 1 E 1 A - \ u 1 E 1 A ] | [ \ u 1 E 1 C - \ u 1 E 1 C ] | [ \ u 1 E 1 E - \ u 1 E 1 E ] | [ \ u 1 E 2 0 - \ u 1 E 2 0 ] | [ \ u 1 E 2 2 - \ u 1 E 2 2 ] | [ \ u 1 E 2 4 - \ u 1 E 2 4 ] | [ \ u 1 E 2 6 - \ u 1 E 2 6 ] | [ \ u 1 E 2 8 - \ u 1 E 2 8 ] | [ \ u 1 E 2 A - \ u 1 E 2 A ] | [ \ u 1 E 2 C - \ u 1 E 2 C ] | [ \ u 1 E 2 E - \ u 1 E 2 E ] | [ \ u 1 E 3 0 - \ u 1 E 3 0 ] | [ \ u 1 E 3 2 - \ u 1 E 3 2 ] | [ \ u 1 E 3 4 - \ u 1 E 3 4 ] | [ \ u 1 E 3 6 - \ u 1 E 3 6 ] | [ \ u 1 E 3 8 - \ u 1 E 3 8 ] | [ \ u 1 E 3 A - \ u 1 E 3 A ] | [ \ u 1 E 3 C - \ u 1 E 3 C ] | [ \ u 1 E 3 E - \ u 1 E 3 E ] | [ \ u 1 E 4 0 - \ u 1 E 4 0 ] | [ \ u 1 E 4 2 - \ u 1 E 4 2 ] | [ \ u 1 E 4 4 - \ u 1 E 4 4 ] | [ \ u 1 E 4 6 - \ u 1 E 4 6 ] | [ \ u 1 E 4 8 - \ u 1 E 4 8 ] | [ \ u 1 E 4 A - \ u 1 E 4 A ] | [ \ u 1 E 4 C - \ u 1 E 4 C ] | [ \ u 1 E 4 E - \ u 1 E 4 E ] | [ \ u 1 E 5 0 - \ u 1 E 5 0 ] | [ \ u 1 E 5 2 - \ u 1 E 5 2 ] | [ \ u 1 E 5 4 - \ u 1 E 5 4 ] | [ \ u 1 E 5 6 - \ u 1 E 5 6 ] | [ \ u 1 E 5 8 - \ u 1 E 5 8 ] | [ \ u 1 E 5 A - \ u 1 E 5 A ] | [ \ u 1 E 5 C - \ u 1 E 5 C ] | [ \ u 1 E 5 E - \ u 1 E 5 E ] | [ \ u 1 E 6 0 - \
Ltmo : /[\u01C5-\u01C5]|[\u01C8-\u01C8]|[\u01CB-\u01CB]|[\u01F2-\u01F2][\u02B0-\u02B8]|[\u02BB-\u02C1]|[\u02D0-\u02D1]|[\u02E0-\u02E4]|[\u037A-\u037A]|[\u0559-\u0559]|[\u0640-\u0640]|[\u06E5-\u06E6]|[\u0E46-\u0E46]|[\u0EC6-\u0EC6]|[\u3005-\u3005]|[\u3031-\u3035]|[\u309D-\u309E]|[\u30FC-\u30FE]|[\uFF70-\uFF70]|[\uFF9E-\uFF9F][\u01AA-\u01AA]|[\u01BB-\u01BB]|[\u01BE-\u01C3]|[\u03F3-\u03F3]|[\u04C0-\u04C0]|[\u05D0-\u05EA]|[\u05F0-\u05F2]|[\u0621-\u063A]|[\u0641-\u064A]|[\u0671-\u06B7]|[\u06BA-\u06BE]|[\u06C0-\u06CE]|[\u06D0-\u06D3]|[\u06D5-\u06D5]|[\u0905-\u0939]|[\u093D-\u093D]|[\u0950-\u0950]|[\u0958-\u0961]|[\u0985-\u098C]|[\u098F-\u0990]|[\u0993-\u09A8]|[\u09AA-\u09B0]|[\u09B2-\u09B2]|[\u09B6-\u09B9]|[\u09DC-\u09DD]|[\u09DF-\u09E1]|[\u09F0-\u09F1]|[\u0A05-\u0A0A]|[\u0A0F-\u0A10]|[\u0A13-\u0A28]|[\u0A2A-\u0A30]|[\u0A32-\u0A33]|[\u0A35-\u0A36]|[\u0A38-\u0A39]|[\u0A59-\u0A5C]|[\u0A5E-\u0A5E]|[\u0A72-\u0A74]|[\u0A85-\u0A8B]|[\u0A8D-\u0A8D]|[\u0A8F-\u0A91]|[\u0A93-\u0AA8]|[\u0AAA-\u0AB0]|[\u0AB2-\u0AB3]|[\u0AB5-\u0AB9]|[\u0ABD-\u0ABD]|[\u0AD0-\u0AD0]|[\u0AE0-\u0AE0]|[\u0B05-\u0B0C]|[\u0B0F-\u0B10]|[\u0B13-\u0B28]|[\u0B2A-\u0B30]|[\u0B32-\u0B33]|[\u0B36-\u0B39]|[\u0B3D-\u0B3D]|[\u0B5C-\u0B5D]|[\u0B5F-\u0B61]|[\u0B85-\u0B8A]|[\u0B8E-\u0B90]|[\u0B92-\u0B95]|[\u0B99-\u0B9A]|[\u0B9C-\u0B9C]|[\u0B9E-\u0B9F]|[\u0BA3-\u0BA4]|[\u0BA8-\u0BAA]|[\u0BAE-\u0BB5]|[\u0BB7-\u0BB9]|[\u0C05-\u0C0C]|[\u0C0E-\u0C10]|[\u0C12-\u0C28]|[\u0C2A-\u0C33]|[\u0C35-\u0C39]|[\u0C60-\u0C61]|[\u0C85-\u0C8C]|[\u0C8E-\u0C90]|[\u0C92-\u0CA8]|[\u0CAA-\u0CB3]|[\u0CB5-\u0CB9]|[\u0CDE-\u0CDE]|[\u0CE0-\u0CE1]|[\u0D05-\u0D0C]|[\u0D0E-\u0D10]|[\u0D12-\u0D28]|[\u0D2A-\u0D39]|[\u0D60-\u0D61]|[\u0E01-\u0E30]|[\u0E32-\u0E33]|[\u0E40-\u0E45]|[\u0E81-\u0E82]|[\u0E84-\u0E84]|[\u0E87-\u0E88]|[\u0E8A-\u0E8A]|[\u0E8D-\u0E8D]|[\u0E94-\u0E97]|[\u0E99-\u0E9F]|[\u0EA1-\u0EA3]|[\u0EA5-\u0EA5]|[\u0EA7-\u0EA7]|[\u0EAA-\u0EAB]|[\u0EAD-\u0EB0]|[\u0EB2-\u0EB3]|[\u0EBD-\u0EBD]|[\u0EC0-\u0EC4]|[\u0EDC-\u0EDD]|[\u0F00-\u0F00]|[\u0F40-\u0F47]|[\u0F49-\u0F69]|[\u0F88-\u0F8B]|[\u1100-\u1159]|[\u115F-\u11A2]|[\u11A8-\u11F9]|[\u2135-\u2138]|[\u3006-\u3006]|[\u3041-\u3094]|[\u30A1-\u30FA]|[\u3105-\u312C]|[\u3131-\u318E]|[\u4E00-\u9FA5]|[\uAC00-\uD7A3]|[\uF900-\uFA2D]|[\uFB1F-\uFB28]|[\uFB2A-\uFB36]|[\uFB38-\uFB3C]|[\uFB3E-\uFB3E]|[\uFB40-\uFB41]|[\uFB43-\uFB44]|[\uFB46-\uFBB1]|[\uFBD3-\uFD3D]|[\uFD50-\uFD8F]|[\uFD92-\uFDC7]|[\uFDF0-\uFDFB]|[\uFE70-\uFE72]|[\uFE74-\uFE74]|[\uFE76-\uFEFC]|[\uFF66-\uFF6F]|[\uFF71-\uFF9D]|[\uFFA0-\uFFBE]|[\uFFC2-\uFFC7]|[\uFFCA-\uFFCF]|[\uFFD2-\uFFD7]|[\uFFDA-\uFFDC]/
} ;
} , { } ] } , { } , [ 3 ] ) ( 3 )
} ) ;