426 Commits (b81396a904fef4992ecd9fdc2b77a0226e2d7ee4)

Author SHA1 Message Date
David Majda 6d82422045 Remove trailing comma in an array literal
It caused an additional newline in generated parsers in IE 8.
9 years ago
David Majda 969d39e8d9 Remove trailing commas in object literals
They broke IE 8-9.
9 years ago
David Majda d5f93a8282 Fix comment typo 9 years ago
David Majda a4772376fb Renumber bytecode instructions sequentially 9 years ago
David Majda ad27a300a8 Fix left recursion detection in sequences
Report left recursion also in cases where the recursive rule invocation
is not a direct element of a sequence, but is wrapped inside an
expression.

Fixes #359.
9 years ago
David Majda cdeecf750f reportLeftRecursion: Change handling of the |visitedRules| array
Before this commit, the |reportLeftRecursion| pass was written in
functional style, passing the |visitedRules| array around as a parameter
and making a new copy each time a rule was visited. This apparently
caused performance problems in some deeply recursive grammars.

This commit makes it so that there is just one array which is shared
across all the visitor functions via a closure and modified as rules are
visited.

I don't like losing the functional style (it was elegant) but
performance is more important.

Fixes #203.
9 years ago
David Majda 4b154e177f Update character categories in grammars to Unicode 8.0.0 9 years ago
David Majda d7d7e87874 Make infinite loop and left recursion detectors work with named rules
Add missing |named| case to the visitor in lib/compiler/asts.js, which
makes the infinite loop and left recursion detectors work correctly with
named rules.

The missing case caused |make parser| to fail with:

  140:34: Infinite loop detected.
  make: *** [parser] Error 1
9 years ago
David Majda 130cbcfaa3 Rename asts.matchesEmpty to alwaysAdvancesOnSuccess and negate it
This makes it more clear that the function isn't about the input the
expression *matched* but about the input it *consumed* when it matched.

Based on a comment by @Mingun:

  https://github.com/pegjs/pegjs/pull/307#issuecomment-89512575
9 years ago
David Majda 5e6b5da4e9 Merge pull request #347 from mbaumgartl/errorstack
Add stack trace in engines based on V8
9 years ago
Marco Baumgartl 940a66fb38 Add stack trace in engines based on V8. Fixes #331 9 years ago
Arlo Breault 12c169e7b5 Convert PEG.js code to strict mode
* Issues #323
9 years ago
Arlo Breault 45e39c3ac8 Make generated parsers use strict mode
* Issue #324

 * JSHint complains about two possible strict violations. But are valid
   uses of `this`, so we suppress the warnings.
9 years ago
Arlo Breault 7285ccfd4e Remove block around initialize code
* In strict mode code, functions can only be declared at top level or
   immediately within another function.  This means functions defined in
   the initializer would throw.
9 years ago
Arlo Breault 7695e5e3c5 Fix complaints from `make hint` 9 years ago
David Majda f2200e48af Optimize location info computation
Before this commit, position details (line and column) weren't computed
efficiently from the current parse position. There was a cache but it
held only one item and it was rarely hit in practice. This resulted in
frequent rescanning of the whole input when the |location| function was
used in various places in a grammar.

This commit extends the cache to remember position details for any
position they were ever computed for. In case of a cache miss, the cache
is searched for a value corresponding to the nearest lower position,
which is then used to compute position info for the desired position
(which is then cached). The whole input never needs to be rescanned.

No items are ever evicted from the cache. I think this is fine as the
max number of entries is the length of the input. If this becomes a
problem I can introduce some eviction logic later.

The performance impact of this change is significant. As the benchmark
suite doesn't contain any grammar with |location| calls I just used a
little ad-hoc benchmark script which measured time to parse the grammar
of PEG.js itself (which contains |location| calls):

  var fs     = require("fs"),
      parser = require("./lib/parser");

  var grammar = fs.readFileSync("./src/parser.pegjs", "utf-8"),
      startTime, endTime;

  startTime = (new Date()).getTime();
  parser.parse(grammar);
  endTime = (new Date()).getTime();

  console.log(endTime - startTime);

The measured time went from ~293 ms to ~54 ms on my machine.

Fixes #337.
9 years ago
David Majda 29bb921994 Rename |peg$cache| to |peg$resultsCache|
This change will make the results cache clearly distinguishable from the
position details cache (which I'll add in a minute).
9 years ago
David Majda eaca5f0acf Add location information to |GrammarError|
This means all errors thrown by |PEG.buildParser| now have associated
location information.
9 years ago
David Majda 89146915ce Add location information to AST nodes
This will allow to add location information to |GrammarError| exceptions
thrown in various passes.
9 years ago
David Majda d1fe86683b Improve location info in tracing events
Replace |line|, |column|, and |offset| properties of tracing events with
the |location| property. It contains an object similar to the one
returned by the |location| function available in action code:

  {
    start: { offset: 23, line: 5, column: 6 },
    end:   { offset: 25, line: 5, column: 8 }
  }

For the |rule.match| event, |start| refers to the position at the
beginning of the matched input and |end| refers to the position after
the end of the matched input.

For |rule.enter| and |rule.fail| events, both |start| and |end| refer to
the current position at the time the rule was entered.
9 years ago
David Majda 065f4e1b75 Improve location info in syntax errors
Replace |line|, |column|, and |offset| properties of |SyntaxError| with
the |location| property. It contains an object similar to the one
returned by the |location| function available in action code:

  {
    start: { offset: 23, line: 5, column: 6 },
    end:   { offset: 25, line: 5, column: 8 }
  }

For syntax errors produced in the middle of the input, |start| refers to
the first unparsed character and |end| refers to the character behind it
(meaning the span is 1 character). This corresponds to the portion of
the input in the |found| property.

For syntax errors produced the end of the input, both |start| and |end|
refer to a character past the end of the input (meaning the span is 0
characters).

For syntax errors produced by calling |expected| or |error| functions in
action code the location info is the same as the |location| function
would return.
9 years ago
David Majda b1ad2a1f61 Rename |reportedPos| to |savedPos|
Preform the following renames:

  * |reportedPos| -> |savedPos| (abstract machine variable)
  * |peg$reportedPos| -> |peg$savedPos| (variable in generated code)
  * |REPORT_SAVED_POS| -> |LOAD_SAVED_POS| (instruction)
  * |REPORT_CURR_POS| -> |UPDATE_SAVED_POS| (instruction)

The idea is that the name |reportedPos| is no longer accurate after the
|location| change (seea the previous commit) because now both
|reportedPos| and |currPos| are reported to user code. Renaming to
|savedPos| resolves this inaccuracy.

There is probably some better name for the concept than quite generic
|savedPos|, but it doesn't come to me.
9 years ago
David Majda 4f7145e360 Improve location info available in action code
Replace |line|, |column|, and |offset| functions with the |location|
function. It returns an object like this:

  {
    start: { offset: 23, line: 5, column: 6 },
    end:   { offset: 25, line: 5, column: 8 }
  }

In actions, |start| refers to the position at the beginning of action's
expression and |end| refers to the position after the end of action's
expression. This allows one to easily add location info e.g. to AST
nodes created in actions.

In predicates, both |start| and |end| refer to the current position.

Fixes #246.
9 years ago
David Majda d7fc0b5c3b Implement infinite loop detection
Fixes #26.
9 years ago
David Majda 95ce20ed92 Extract the |matchesEmpty| visitor from the |reportLeftRecursion| pass
Beside the recursion detector, the visitor will also be used by infinite
loop detector.

Note the newly created |asts.matchesEmpty| function re-creates the
visitor each time it is called, which makes it slower than necessary.
This could have been worked around in various ways but I chose to defer
that optimization because real-world performance impact is small.
9 years ago
David Majda 03a391e874 s/appliedRules/visitedRules/
The rules are not really *applied* by the |reportLeftRecursion| pass,
they are just *visited*.
9 years ago
David Majda 25ed2b7ee2 Improve comment describing the |reportLeftRecursion| pass 9 years ago
David Majda 6ce97457bf Fix left recursion detection
So far, left recursion detector assumed that left recursion occurs only
when the recursive rule is at the very left-hand side of rule's
expression:

  start = start

This didn't catch cases like this:

  start = "a"? start

In general, if a rule reference can be reached without consuming any
input, it can lead to left recursion. This commit fixes the detector to
consider that.

Fixes #190.
9 years ago
David Majda da57118a43 Implement basic support for tracing
Parsers can now be generated with support for tracing using the --trace
CLI option or a boolean |trace| option to |PEG.buildParser|. This makes
them trace their progress, which can be useful for debugging. Parsers
generated with tracing support are called "tracing parsers".

When a tracing parser executes, by default it traces the rules it enters
and exits by writing messages to the console. For example, a parser
built from this grammar:

  start = a / b
  a = "a"
  b = "b"

will write this to the console when parsing input "b":

  1:1 rule.enter start
  1:1 rule.enter   a
  1:1 rule.fail    a
  1:1 rule.enter   b
  1:2 rule.match   b
  1:2 rule.match start

You can customize tracing by passing a custom *tracer* to parser's
|parse| method using the |tracer| option:

  parser.parse(input, { trace: tracer });

This will replace the built-in default tracer (which writes to the
console) by the tracer you supplied.

The tracer must be an object with a |trace| method. This method is
called each time a tracing event happens. It takes one argument which is
an object describing the tracing event.

Currently, three events are supported:

  * rule.enter -- triggered when a rule is entered
  * rule.match -- triggered when a rule matches successfully
  * rule.fail  -- triggered when a rule fails to match

These events are triggered in nested pairs -- for each rule.enter event
there is a matching rule.match or rule.fail event.

The event object passed as an argument to |trace| contains these
properties:

  * type   -- event type
  * rule   -- name of the rule the event is related to
  * offset -- parse position at the time of the event
  * line   -- line at the time of the event
  * column -- column at the time of the event
  * result -- rule's match result (only for rule.match event)

The whole tracing API is somewhat experimental (which is why it isn't
documented properly yet) and I expect it will evolve over time as
experience is gained.

The default tracer is also somewhat bare-bones. I hope that PEG.js user
community will develop more sophisticated tracers over time and I'll be
able to integrate their best ideas into the default tracer.
9 years ago
David Majda 675561f085 Rename and generalize |generateCache{Header,Footer}|
Rename |generateCache{Header,Footer}| to |generateRule{Header,Footer}|
and change their responsibility to generate overall header/footer of a
rule function (when optimizing for speed) or the |peg$parseRule|
function (when optimizing for speed). This creates a natural place where
to generate tracing code (coming soon).
9 years ago
David Majda fb5f6c6ee9 Make labels behave like block-scoped variables
Action and predicate code can now see variables defined in expressions
"above" them.

Based on a pull request by Bryon Vandiver (@asterick):

  https://github.com/pegjs/pegjs/pull/180

Fixes #316.
9 years ago
David Majda fb7de36051 Update website URL
PEG.js website was moved from http://pegjs.majda.cz/ to http://pegjs.org/.
10 years ago
David Majda 0977dd37a3 Reordering in visitors and their specs
Reorder visiting functions and their specs to more closely match
ordering used in the PEG.js grammar.
10 years ago
David Majda 4ec9e6ba10 Remove useless test in the |reportLeftRecursion| pass
Empty sequences are not allowed anymore so we don't have to test for
them.
10 years ago
David Majda 898a7b5a2d Simplify visitors by providing default visit functions
The |visitor.build| function now supplies default visit functions for
visitors it builds. These functions don't do anything beside traversing
the tree and passing arguments around to child visit functions.

Having the default visit functions allowed to simplify several visitors.
10 years ago
David Majda f457c41dd4 Declare the |j| variable before use in lib/utils/arrays.js
Until now it was inadvertently global.
10 years ago
David Majda 24394e3f91 Fix comment alignment in lib/compiler/passes/generate-javascript.js 10 years ago
David Majda 2b06476c69 Regenerate lib/parser.js after bytecode changes 10 years ago
David Majda dad1207c46 Improve semantics of the TEXT bytecode instruction
The TEXT instruction now replaces position at the top of the stack with
the input from that position until the current position. This is simpler
and cleaner semantics than the previous one, where TEXT also popped an
additional value from the stack and kept the position there.
10 years ago
David Majda a815a8b902 Implement additional PUSH_* bytecode instructions
Implement the following bytecode instructions:

  * PUSH_UNDEFINED
  * PUSH_NULL
  * PUSH_FAILED
  * PUSH_EMPTY_ARRAY

These instructions push simple JavaSccript values to the stack directly,
without going through constants. This makes the bytecode slightly
shorter and the bytecode generator somewhat simpler.

Also note that PUSH_EMPTY_ARRAY allows us to avoid a hack which protects
the [] constant from modification.
10 years ago
David Majda 85c8f386c1 Formatting 10 years ago
David Majda f03ba4bf4f generate-javascript.js: s/generateJavaScript/generateJavascript/
This makes the variable name in sync with pass name in lib/compiler.js.
10 years ago
David Majda 57f7fae684 Fix a bug in |stringEscape|
The |stringEscape| function both in lib/compiler/javascript.js and in
generated parsers didn't escape characters in the U+0100..U+107F and
U+1000..U+107F ranges.
10 years ago
David Majda 88e5f136e1 Utility functions cleanup: Cleanup lib/compiler/javascript.js 10 years ago
David Majda c1e1502d43 Utility functions cleanup: Cleanup lib/compiler/visitor.js 10 years ago
David Majda bfaad70899 Utility functions cleanup: Cleanup lib/compiler/asts.js 10 years ago
David Majda 05f97f444d Utility functions cleanup: Cleanup lib/utils/classes.js 10 years ago
David Majda 1582304f16 Utility functions cleanup: Cleanup lib/utils/objects.js 10 years ago
David Majda 50b2054fbf Utility functions cleanup: Cleanup lib/utils/arrays.js 10 years ago
David Majda 5adad3ae12 Utility functions cleanup: Split lib/utils.js
Split lib/utils.js into multiple files. Some of the functions were
generic, these were moved into files in lib/utils. Other funtions were
specific for the compiler, these were moved to files in lib/compiler.

This commit only moves functions around -- there is no renaming and
cleanup performed. Both will come later.
10 years ago
David Majda ff8e877fce Change module exporting style
Modules now generally store the exported object in a named variable or
function first and only assign |module.exports| at the very end. This is
a difference when compared to style used until now, where most modules
started with a |module.exports| assignment.

I think the explicit name helps readability and understandability.
10 years ago
David Majda d9354c4632 Standardize on 3 spaces before // comments 10 years ago
David Majda f3a83788aa Inline functions extracted just because of JSHint
Rather than extracting functions just because JSHint complained about
defining functions inside a loop, let's inline then and silence the
warning.
10 years ago
David Majda 46ac1bf171 Wrap initializer code in generated parsers into |{...}|
Initializer code is usually indented and this indentation is carried
over to generated code. This resulted in a piece of indented code in the
middle of the parser.

This commit wraps initializer code in |{...}|, which makes indentation
in generated parsers look a bit more natural.
10 years ago
David Majda 39084496ca Expose the parser object in action/predicate code
The action/predicate code didn't have access to the parser object. This
was mostly a side effect actions/predicates being implemented as nested
functions, in which |this| is a reference to the global object (an ugly
JavaScript quirk). The initializer, being implemented differently, had
access to the parser object via |this|, but this was not documented.

Because having access to the parser object can be useful, this commits
introduces a new |parser| variable which holds a reference to it, is
visible in action/predicate/initializer code, and is properly
documented.

See also:

  https://groups.google.com/forum/#!topic/pegjs/Na7YWnz6Bmg
10 years ago
David Majda c7521fb868 Mark |parse| and |SyntaxError| as internal identifiers
The |parse| function and the |SyntaxError| exception were meant as
internal, so let's mark them as such.
10 years ago
David Majda 7e3b4ec4f8 PEG.js grammar: Remove reserved word detection
This is mostly done for consistency with the JavaScript example grammar,
from which the |Identifier| rule is taken from. See the previous commit
for details.
10 years ago
David Majda e78ffbba9c PEG.js grammar: Improve the |Code| rule a bit
Instead of matching segments between blocks character by character,
match them as a whole. Also align the style with other similar rules
(e.g. the comment ones).
10 years ago
David Majda 64eb5faf54 PEG.js grammar: Fix line continuation handling in character classes
Before this commit, line continuations in character classes contributed
an empty string to the list of characters and character ranges matched
by a class. While this didn't lead to a buggy behavior with the current
code generator, the AST was wrong and the problem could have caused bugs
later.

This commit fixes the problem.
10 years ago
David Majda 0678bd8a0c PEG.js grammar: Add missing semicolon
Fixes the following JSHint error:

  lib/parser.js: line 108, col 54, Missing semicolon.
10 years ago
David Majda 0459ab6b37 PEG.js grammar: Formatting & comments 10 years ago
David Majda 6f2510e49e PEG.js grammar: Make rules with operators more generic 10 years ago
David Majda 45c29a886f PEG.js grammar: Extract the |SemanticPredicateExpression| rule
Semantic predicates are kind of |PrimaryExpression|, not kind of
|PrefixedExpression|. Therefore I extracted a rule for them and
referenced it from the |PrimaryExpression|.
10 years ago
David Majda da18f6a729 PEG.js grammar: Extract the |RuleReferenceExpression| rule
This makes the |Primary| rule a bit more tidy.
10 years ago
David Majda 8e6f98e45c PEG.js grammar: Extract the |ActionExpression| rule
Having it separated from the |SequenceExpression| rule is cleaner and
more logical.
10 years ago
David Majda 5c6f4dd38b PEG.js grammar: Append |Expression| to expression rule names
Makes the rule names a bit longer but also clearer.
10 years ago
David Majda 27c2d26203 PEG.js grammar: More JavaScript-like initializer/rule separation
Initializer and rules are now separated in a similar way as JavaScript
statements -- either by a semicolon or a line terminator, possibly with
whitespace and comments mixed in.

One consequence is that the grammars like this are now illegal:

  foo = "a" bar = "b"

A semicolon needs to be inserted between the rules:

  foo = "a";bar = "b"

I consider this a good change as the now-illegal syntax was somewhat
confusing.
10 years ago
David Majda 4ce7593f5f PEG.js grammar: Extract the |AnyMatcher| rule
This makes the |Primary| rule a bit more tidy. Also, matching the |.|
character really belongs to the lexical part of the grammar, next to
literals and character classes.
10 years ago
David Majda c0df01b092 PEG.js grammar: Improve code block handling
* Rename the |Action| rule to |CodeBlock| (it better describes what
    the rule matches).

  * Implement the rule in a simpler way and move it after more basic
    lexical elements.
10 years ago
David Majda 13f72bb19d PEG.js grammar: More JavaScript-like rules for identifiers
This change has two side effects:

  * Label names can no longer be JavaScript reserved words.

  * |$| is allowed again in label names. However, because of the
    preference rules, names starting with it will be usually parsed as a
    text operator followed by another identifier (denoting a rule
    reference or label name).
10 years ago
David Majda 0d6b91cb20 PEG.js grammar: More JavaScript-like rules for strings/literals/classes 10 years ago
David Majda bcb5271649 PEG.js grammar: More JavaScript-like rules for skipped elements 10 years ago
David Majda a5a0609505 PEG.js grammar: Inline trivial character rules 10 years ago
David Majda ae89f5e469 PEG.js grammar: Change whitespace handling
Before this commit, whitespace was handled at the lexical level by
making tokens consume any whitespace coming after them. This was
accomplished by appending |__| to every token rule.

This commit changes whitespace handling to be more explicit. Tokens no
longer consume whitespace coming after them and syntactic rules have to
cope with it. While this slightly complicates the syntactic grammar, I
think it's a cleaner way. Moreover, it is what JavaScript example
grammar does.

One small side-effect of thich change is that the grammar is now
stand-alone (it doesn't require utils.js anymore).
10 years ago
David Majda 4725632641 PEG.js grammar: Capitalize rule names
When rule names are capitalized, it's easier to visually distinguish
them from non-capitalized label names. Moreover, I use capitalized rule
names in all my grammars these days.
10 years ago
David Majda fb72c430e6 PEG.js grammar: Fix line continuation handling
Before this commit, a line continuation (backslash followed by a line
terminator character) contributed a character to a string or a character
class it was used in. In JavaScript and many other languages, line
continuation doesn't contribute anything.

This commit aligns PEG.js line continuation behavior with JavaScript.
10 years ago
David Majda 3dbec0b30d PEG.js grammar: Fix how |rawText| is created
Before this commit, the value of the |rawText| property of "class" AST
nodes was created in a hackish way from processed input and it didn't
always exactly represent the actual input text.

This commit changes the code so that the value of the |rawText| property
is created using the |text| function. This is a clean way which also
resolves the exact representation problem.
10 years ago
David Majda df154daafb PEG.js grammar: Disallow empty sequences
Empty sequences are useless and they only confused users. Let's disallow
them.
10 years ago
David Majda 2263a30034 Update version to 0.8.0 10 years ago
David Majda 95fd64ec15 .jshintrc: Add the "forin" option & fix fallout
Also added few missing |hasOwnProperty| calls that JSHint didn't detect
because it only looks whether there is an |if| statement wrapping the
loop body.
11 years ago
David Majda e321f0c23e Fix JSHint error in lib/compiler/passes/generate-bytecode.js
Fixes the following JSHint error:

  lib/compiler/passes/generate-bytecode.js: line 334, col 71, Expected an assignment or function call and instead saw an expression.
11 years ago
David Majda 06a83448df Remove various unused variables and function parameters 11 years ago
David Majda 976328b7d6 Avoid |Array.prototype.splice| call with one parameter
The one-parameter |Array.prototype.splice| call is a SpiderMonkey
extension. Apparently, IE doesn't implement it (unlike other supported
browsers), so we need to replace it with two-parameter version.
11 years ago
David Majda a56d3ac94f Fix error messages in certain cases with trailing input
In case the generated parser parsed successfully part of input and left
some input unparsed (trailing input), the error message produced was
sometimes wrong. The code worked correctly only if there were no match
failures in the successfully parsed part (highly unlikely).

This commit fixes things by explicitly triggering a match failure with the
following expectation at the end of the successfully parsed part of the
input:

  peg$fail({ type: "end", description: "end of input" });

This change also made it possible to simplify the |buildMessage|
function, which can now ignore the case of no expectations.

Fixes #119.
11 years ago
David Majda 44e03187a7 Assert that generated bytecode manipulates stack correctly
There are two invariants in generated bytecode related to the stack:

  1. Branches of a condition must move the stack pointer in the same way.

  2. Body of a loop can't move the stack pointer.

These invariants were always true, but they were not checked. Now we
check them at least when compiling with optimization for speed, because
there we analyze the stack pointer movements statically.
11 years ago
David Majda 0bcf7bc61b Renumber bytecode instructions to make them sequential 11 years ago
David Majda 9ca5061fcf lib/compiler/opcodes.js: Fix formatting 11 years ago
David Majda 187f9d6bb0 Remove the |NIP_CURR_POS| bytecode instruction
After the previous commit is is not used anywhere.
11 years ago
David Majda e15c57066c Remove an error check after calling action code
The error check was useful when actions could have returned |null| to
trigger a match failure. This is no longer supported so the check isn't
needed anymore.

Speed impact
------------
Before:     1022.70 kB/s
After:      1035.45 kB/s
Difference: 1.24%

Size impact
-----------
Before:     975434 b
After:      931540 b
Difference: -4.50%

(Measured by /tools/impact with Node.js v0.6.18 on x86_64 GNU/Linux.)
11 years ago
David Majda 2f2152204a Refine error handling further
Before this commit, the |expected| and |error| functions didn't halt the
parsing immediately, but triggered a regular match failure. After they
were called, the parser could backtrack, try another branches, and only
if no other branch succeeded, it triggered an exception with information
possibly based on parameters passed to the |expected| or |error|
function (this depended on positions where failures in other branches
have occurred).

While nice in theory, this solution didn't work well in practice. There
were at least two problems:

  1. Action expression could have easily triggered a match failure later
     in the input than the action itself. This resulted in the
     action-triggered failure to be shadowed by the expression-triggered
     one.

     Consider the following example:

       integer = digits:[0-9]+ {
         var result = parseInt(digits.join(""), 10);

         if (result % 2 === 0) {
           error("The number must be an odd integer.");
           return;
         }

         return result;
       }

     Given input "2", the |[0-9]+| expression would record a match
     failure at position 1 (an unsuccessful attempt to parse yet another
     digit after "2"). However, a failure triggered by the |error| call
     would occur at position 0.

     This problem could have been solved by silencing match failures in
     action expressions, but that would lead to severe performance
     problems (yes, I tried and measured). Other possible solutions are
     hacks which I didn't want to introduce into PEG.js.

  2. Triggering a match failure in action code could have lead to
     unexpected backtracking.

     Consider the following example:

       class = "[" (charRange / char)* "]"

       charRange = begin:char "-" end:char {
         if (begin.data.charCodeAt(0) > end.data.charCodeAt(0)) {
           error("Invalid character range: " + begin + "-" + end + ".");
         }

         // ...
       }

       char = [a-zA-Z0-9_\-]

     Given input "[b-a]", the |charRange| rule would fail, but the
     parser would try the |char| rule and succeed repeatedly, resulting
     in "b-a" being parsed as a sequence of three |char|'s, which it is
     not.

     This problem could have been solved by using negative predicates,
     but that would complicate the grammar and still wouldn't get rid of
     unintuitive behavior.

Given these problems I decided to change the semantics of the |expected|
and |error| functions. They don't interact with regular match failure
mechanism anymore, but they cause and immediate parse failure by
throwing an exception. I think this is more intuitive behavior with less
harmful side effects.

The disadvantage of the new approach is that one can't backtrack from an
action-triggered error. I don't see this as a big deal as I think this
will be rarely needed and one can always use a semantic predicate as a
workaround.

Speed impact
------------
Before:     993.84 kB/s
After:      998.05 kB/s
Difference: 0.42%

Size impact
-----------
Before:     1019968 b
After:      975434 b
Difference: -4.37%

(Measured by /tools/impact with Node.js v0.6.18 on x86_64 GNU/Linux.)
11 years ago
David Majda 9fa7301aec Regenerate src/parser.js
Forgot to do it in f8b5e04bba.
11 years ago
David Majda 5460a881af Error handling: Implement the |error| function
The |error| function allows users to report custom match failures inside
actions.

If the |error| function is called, and the reported match failure turns
out to be the cause of a parse error, the error message reported by the
parser will be exactly the one specified in the |error| call.

Implements part of #198.

Speed impact
------------
Before:     999.83 kB/s
After:      1000.84 kB/s
Difference: 0.10%

Size impact
-----------
Before:     1017212 b
After:      1019968 b
Difference: 0.27%

(Measured by /tools/impact with Node.js v0.6.18 on x86_64 GNU/Linux.)
11 years ago
David Majda dd74ea4144 Error handling: Build error message out of |SyntaxError|'s constructor
It will be possible to create errors with user-supplied messages soon.
The |SyntaxError| class needs to be ready for that.

Implements part of #198.
11 years ago
David Majda 3fe6aba7e2 Error handling: Extract exception building into its own function
The exception-creating code will get somewhat hairy soon, so let's make
sure them mess will be contained.

Implements part of #198.
11 years ago
David Majda d96eb317fd Error handling: Rename |peg$fail| to |peg$expected|
This is in anticipation of |peg$error|. The |peg$expected| and
|peg$error| internal functions will nicely mirror the |expected| and
|error| functions available to user code in actions.

Implements part of #198.
11 years ago
David Majda af701dcf80 Error handling: Implement the |expected| function
The |expected| function allows users to report regular match failures
inside actions.

If the |expected| function is called, and the reported match failure
turns out to be the cause of a parse error, the error message reported
by the parser will be in the usual "Expected ... but found ..." format
with the description specified in the |expected| call used as part of
the message.

Implements part of #198.

Speed impact
------------
Before:     1146.82 kB/s
After:      1031.25 kB/s
Difference: -10.08%

Size impact
-----------
Before:     950817 b
After:      973269 b
Difference: 2.36%

(Measured by /tools/impact with Node.js v0.6.18 on x86_64 GNU/Linux.)
11 years ago
David Majda 1b2279e026 Error handling: Make predicates always return |undefined|
After making the |?| operator return |null| instead of an empty string
in the previous commit, empty strings were still returned from
predicates. This didn't make much sense.

Return value of a predicate is unimportant (if you have one in hand, you
already know the predicate succeeded) and one could even argue that
predicates shouldn't return any value at all. The closest thing to
"return no value" in JavaScript is returning |undefined|, so I decided
to make predicates return exactly that.

Implements part of #198.
11 years ago
David Majda 86769a6c5c Error handling: Make |?| return |null| on unsuccessful match
Before this commit, the |?| operator returned an empty string upon
unsuccessful match. This commit changes the returned value to |null|. It
also updates the PEG.js grammar and the example grammars, which used the
value returned by |?| quite often.

Returning |null| is possible because it no longer indicates a match
failure.

I expect that this change will simplify many real-world grammars, as an
empty string is almost never desirable as a return value (except some
lexer-level rules) and it is often translated into |null| or some other
value in action code.

Implements part of #198.
11 years ago
David Majda 57e806383c Error handling: Use a special value (not |null|) to indicate failure
Using a special value to indicate match failure instead of |null| allows
actions to return |null| as a regular value. This simplifies e.g. the
JSON parser.

Note the special value is internal and intentionally undocumented. This
means that there is currently no official way how to trigger a match
failure from an action. This is a temporary state which will be fixed
soon.

The negative performance impact (see below) is probably caused by
changing lot of comparisons against |null| (which likely check the value
against a fixed constant representing |null| in the interpreter) to
comparisons against the special value (which likely check the value
against another value in the interpreter).

Implements part of #198.

Speed impact
------------
Before:     1146.82 kB/s
After:      1031.25 kB/s
Difference: -10.08%

Size impact
-----------
Before:     950817 b
After:      973269 b
Difference: 2.36%

(Measured by /tools/impact with Node.js v0.6.18 on x86_64 GNU/Linux.)
11 years ago
David Majda 435bb8f2df Error handling: Structured expectations
Before this commit, the |expected| property of an exception object
thrown when a generated parser encountered an error contained
expectations as strings. These strings were in a human-readable format
suitable for displaying in the UI but not suitable for machine
processing. For example, expected string literals included quotes and a
string "any character" was used when any character was expected.

This commit makes expectations structured objects. This makes the
machine processing easier, while still allowing to generate a
human-readable representation if needed.

Implements part of #198.

Speed impact
------------
Before:     1180.41 kB/s
After:      1165.31 kB/s
Difference: -1.28%

Size impact
-----------
Before:     863523 b
After:      950817 b
Difference: 10.10%

(Measured by /tools/impact with Node.js v0.6.18 on x86_64 GNU/Linux.)
11 years ago
David Majda 5312e124cd Fix object literal formatting in generated code 11 years ago
David Majda c6efb337f1 Fix bytecode built for nested sequences inside actions
In the bytecode generator, the |context.action| property wasn't
correctly reset when generating bytecode for sequence elements. As a
result, when a sequence was wrapped in an action and it contained
another sequence as an element, the generator thought that the inner
sequence was wrapped in an action too.

For example, the following grammar:

  start = ("a" "b") "c" { return "x"; }

was compiled as if it looked like this:

  start = ("a" "b" { return "x"; }) "c" { return "x"; }

This commit fixes the problem by resetting |context.action| correctly.

Fixes GH-168.
11 years ago
David Majda 379f5c5eef Regenerate src/parser.js
It wasn't done in beb557d7d3.
11 years ago
David Majda 74636638d0 Merge pull request #196 from vrana/comma
Add whitespace to generated action calls
11 years ago
Jakub Vrana beb557d7d3 Add whitespace to generated action calls
Avoids implicit array to string conversion.
11 years ago
Jakub Vrana 62d151cb5a Fix typo in comment 11 years ago
David Majda 798ed6a8a4 Regenerate src/parser.js
Forgot to do it in 0df8989f7a.

Part of a fix of GH-152.
11 years ago
David Majda 34fe2c01ae Fix matching of case-instensitive literals
Code that calculated which part of the input to match against a literal
was wrong in case of case-insensitive literals when generating
speed-optimized parsers. As a result, matching of case-insensitive
literals worked only at the end of the input (where too big length
passed to the |substr| method didn't matter).

Fixes GH-153.
11 years ago
David Majda 0df8989f7a Fix buggy position computation
Fixes GH-152.
11 years ago
David Majda 76cc5d55b4 Use the |s| function instead of hardcoded |s0| value
Based on a patch by @fresheneesz:

  https://github.com/dmajda/pegjs/pull/148
11 years ago
David Majda 8759d4899e Fix deduplication in |peg$cleanupExpected|
The deduplication skipped over an expected string right after the one
that was removed because the index variable was incorrectly incremented
in that case.

Based on a patch by @fresheneesz:

  https://github.com/dmajda/pegjs/pull/146
11 years ago
David Majda e4b5588327 Plugin API: Split compiler passes into stages
The compiler passes are now split into three stages:

  * check -- passes that check for various error conditions

  * transform -- passes that transform the AST (e.g. to perform
    optimizations)

  * generate -- passes that are related to code generation

Splitting the passes into stages is important for plugins. For example,
if a plugin wants to add a new optimization pass, it can add it at the
end of the "transform" stage without any knowledge about other passes it
contains. Similarly, if it wants to generate something else than the
default code generator does from the AST, it can just replace all passes
in the "generate" stage by its own one(s).

More generally, the stages make it possible to write plugins that do not
depend on names and actions of specific passes (which I consider
internal and subject of change), just on the definition of stages (which
I consider a public API with to which semver rules apply).

Implements part of GH-106.
11 years ago
David Majda 76f5c88073 Plugin API: Implement the |plugins| option for |PEG.buildParser|
The |plugins| option allows users to use plugins that change how PEG.js
operates.

A plugin is any JavaScript object with a |use| method. After the user
calls |PEG.buildParser|, this method is called for each plugin with the
following two parameters:

  * PEG.js config that describes used grammar parser and compiler
    passes used to generate the parser

  * options passed by user to |PEG.buildParser|

The plugin is expected to change the config as needed, possibly based on
the options passed by user. It can e.g. change the used grammar parser,
change the compiler passes (including adding its own), etc. This way it
can extend PEG.js in a flexible way.

Implements part of GH-106.
11 years ago
David Majda d02098eebe Plugin API: Implement the |passes| parameter for |PEG.compiler.compile|
The |passes| parameter will allow to pass the list of passes from
|PEG.buildParser|. This will be used by plugins. The old way via setting
the |appliedPassNames| property is removed.

Implements part of GH-106.
11 years ago
David Majda 3b3798fa39 Merge lib/compiler/passes.js into lib/compiler.js
It didn't make sense to have the passes in a separate file.
11 years ago
David Majda 02af83f9b4 s/subclass/peg$subclass/
The |subclass| function is not intended to be used by user code.
11 years ago
David Majda 4fe32cee8c Fix indentation 11 years ago
David Majda f985bd76ed Fix opcodes in comment in generate-bytecode.js 11 years ago
David Majda c7481d4da1 Test property presence in |utils.defaults| using |in|
This is more correct than comparing to |undefined|.
11 years ago
David Majda d3d4ace153 Move options handling from passes to |PEG.compiler.compile|
This eliminates some duplicate code.
11 years ago
David Majda 5942988f66 Remove the |startRule| property from the AST
It's redundant.
11 years ago
David Majda 3981433984 Fix too eager proxy rules removal
Fixes GH-137.
11 years ago
David Majda 549d052710 Make |GrammarError| require work also in the browser version
Fixes a bug from ac179cda7b (a fix for
GH-135).
11 years ago
David Majda 09f3f83e1c Merge pull request #135 from hyperpape/master
PEG.GrammarError is undefined in report-missing-rules and report-left-recursion
11 years ago
David Majda fe1ca481ab Code generator rewrite
This is a complete rewrite of the PEG.js code generator. Its goals are:

  1. Allow optimizing the generated parser code for code size as well as
     for parsing speed.

  2. Prepare ground for future optimizations and big features (like
     incremental parsing).

  2. Replace the old template-based code-generation system with
     something more lightweight and flexible.

  4. General code cleanup (structure, style, variable names, ...).

New Architecture
----------------

The new code generator consists of two steps:

  * Bytecode generator -- produces bytecode for an abstract virtual
    machine

  * JavaScript generator -- produces JavaScript code based on the
    bytecode

The abstract virtual machine is stack-based. Originally I wanted to make
it register-based, but it turned out that all the code related to it
would be more complex and the bytecode itself would be longer (because
of explicit register specifications in instructions). The only downsides
of the stack-based approach seem to be few small inefficiencies (see
e.g. the |NIP| instruction), which seem to be insignificant.

The new generator allows optimizing for parsing speed or code size (you
can choose using the |optimize| option of the |PEG.buildParser| method
or the --optimize/-o option on the command-line).

When optimizing for size, the JavaScript generator emits the bytecode
together with its constant table and a generic bytecode interpreter.
Because the interpreter is small and the bytecode and constant table
grow only slowly with size of the grammar, the resulting parser is also
small.

When optimizing for speed, the JavaScript generator just compiles the
bytecode into JavaScript. The generated code is relatively efficient, so
the resulting parser is fast.

Internal Identifiers
--------------------

As a small bonus, all internal identifiers visible to user code in the
initializer, actions and predicates are prefixed by |peg$|. This lowers
the chance that identifiers in user code will conflict with the ones
from PEG.js. It also makes using any internals in user code ugly, which
is a good thing. This solves GH-92.

Performance
-----------

The new code generator improved parsing speed and parser code size
significantly. The generated parsers are now:

  * 39% faster when optimizing for speed

  * 69% smaller when optimizing for size (without minification)

  * 31% smaller when optimizing for size (with minification)

(Parsing speed was measured using the |benchmark/run| script. Code size
was measured by generating parsers for examples in the |examples|
directory and adding up the file sizes. Minification was done by |uglify
--ascii| in version 1.3.4.)

Final Note
----------

This is just a beginning! The new code generator lays a foundation upon
which many optimizations and improvements can (and will) be made.

Stay tuned :-)
11 years ago
Justin Blank b58533ec2f Merge branch 'master' of https://github.com/dmajda/pegjs 12 years ago
Justin Blank ac179cda7b Fix ReferenceError in compiler passes.
Previously, the report-left-recursion and report-missing-rules passes
used PEG.GrammarError without requiring it, causing a ReferenceError.

Since requiring lib/peg.js would cause circular requirements, this
commit imports lib/grammar-error.js as GrammarError.

The bug was introduced in commit
4cda79951a.

Fixes GH-135.
12 years ago
David Majda bea6b1fde7 Implement the |text| function
When called inside an action, the |text| function returns the text
matched by action's expression. It can be also called inside an
initializer or a predicate where it returns an empty string.

The |text| function will be useful mainly in cases where one needs a
structured representation of the input and simultaneously the raw text.
Until now, the only way to get the raw text in these cases was to
painfully build it from the structured representation.

Fixes GH-131.
12 years ago
David Majda f0a6bc92cc Text nodes: Use text nodes in PEG.js grammar 12 years ago
David Majda 5e146fce38 Text nodes: Implement text nodes
Implement a new syntax to extract matched strings from expressions. For
example, instead of:

  identifier = first:[a-zA-Z_] rest:[a-zA-Z0-9_]* { return first + rest.join(""); }

you can now just write:

  identifier = $([a-zA-Z_] [a-zA-Z0-9_]*)

This is useful mostly for "lexical" rules at the bottom of many
grammars.

Note that structured match results are still built for the expressions
prefixed by "$", they are just ignored. I plan to optimize this later
(sometime after the code generator rewrite).
12 years ago
David Majda af20f024c7 Text nodes: Disallow the "$" character in identifiers
The "$" character will mark text nodes in the future.
12 years ago
David Majda 4e46a6e46e Rebuild src/parser.js (forgotten in the previous commit) 12 years ago
David Majda 28860e88df Position tracking: Cache position info computed by |line| and |column|
Cache the last reported position info. If the position advances, the
code uses the cache and only computes the differnece. If the position
goes back, the cache is simply dropped.
12 years ago
David Majda 3333cdd18d Position tracking: Kill the |trackLineAndColumn| option
Getting rid of the |trackLineAndColumn| simplifies the code generator
(by unifying two paths in the code).

The |line| and |column| functions currently always compute all the
position info from scratch, which is horribly ineffective. This will be
improved in later commit(s).
12 years ago
David Majda da8c455640 Position tracking: Make |offset|, |line| and |column| functions
This will allow to compute position data lazily and get rid of the
|trackLineAndColumn| option without affecting performance of generated
parsers that don't use position data.
12 years ago
David Majda bc9a2528ef Add backslash forgotten in the previous commit 12 years ago
David Majda 1988110a28 Fix code generated for classes starting with "\^"
Before this commit, incorrect regexps were produced for classes starting
with "\^". For example, this grammar:

  start = [\^a]

didn't match "a" because the generated regexp inside the parser was
/^[^a]/, not /^[\^a]/ as it should be.

This commit fixes the issue by escaping "^" in |quoteForRegexpClass|.

Fixes GH-125.
12 years ago
David Majda ff819cc579 Fix whitespace 12 years ago
David Majda 05a6bad989 Kill the |toSource| method, introduce the |output| option
Before this commit, |PEG.buildParser| always returned a parser object.
The only way to get its source code was to call the |toSource| method on
it. While this method worked for parsers produced by |PEG.buildParser|
directly, it didn't work for parsers instantiated by executing their
source code. In other words, it was unreliable.

This commit remvoes the |toSource| method on generated parsers and
introduces a new |output| option to |PEG.buildParser|. It allows callers
to specify whether they want to get back the parser object
(|options.output === "parser"|) or its source code (|options.output ===
"source"|). This is much better and more reliable API.
12 years ago
David Majda 3629d880d3 Make sure the |options| param passed to passes is always an object
Pass code can be simpler as a result.
12 years ago
David Majda 0519d7e3ce Git repo npmization: Make the repo a npm package
Includes:

  * Moving the source code from /src to /lib.
  * Adding an explicit file list to package.json
  * Updating the Makefile.
  * Updating the spec and benchmark suites and their READMEs.

Part of a fix for GH-32.
12 years ago
David Majda e59f3ba338 Split the source code into several files, introduce build system
The source code is now in the src directory. The library needs to be
built using "rake", which creates the lib/peg.js file by combining the
source files.
14 years ago
David Majda 95a78892de Rename |PEG.compiler.compileParser| to |PEG.compiler.compile|
It's shorter and more consistent with |PEG.parser.parse|.
14 years ago
David Majda 5e64d09a15 Renamed some properties of the |PEG| object
1. |PEG.Compiler| -> |PEG.compiler|
2. |PEG.grammarParser| -> |PEG.parser|

This brings us closer to the desired structure of the PEG object, which
is:

  +-PEG
    |- parser
    +- compiler
       |- checks
       |- passes
       +- emitter

These are the only things (together with the |PEG.buildParser| function
and exceptions) that I want to be publicly accessible -- as extension
points and also for easy testing of PEG.js's components.
14 years ago
David Majda 1682a25b0d Move emitter utility functions out of |PEG.Compiler| 14 years ago
David Majda e5a5572a87 Factored the code emitter out of the compiler 14 years ago
David Majda 2622f432bd Move compiler checks and passes out of |PEG.Compiler| definition
This allows splitting them into separate files in the future. It also
decreases indentation level in the code.
14 years ago
David Majda d7d1a0b28c Remove unused |PEG.ArrayUtils.range| utility function 14 years ago
David Majda 98da358ef4 Found a neater trick how to defend against |undefined| redefinition 14 years ago
David Majda af1968054b Implement semantic predicates 14 years ago
David Majda 4895f4f8e4 Treat the whole grammar as an AST node 14 years ago
David Majda 917cf1cf2a Start rule of the grammar is now implicitly its first rule
Before this change, the start rule was the one named "start" and there
was an option to override that. This is now impossible.

The goal of this change is to contain all information for the parser
generation in the grammar itself.

In the future, some override directive for the start rule (like Bison's
"%start") may be added to the grammar.
14 years ago
David Majda 70cf4cd94d Reset generated variable names for each rule parsing function
Little change in the source grammar now does not change variables in all
the generated code. This is helpful especially when one has the
generated grammar stored in a VCS (this is true e.g. for our
metagrammar).
14 years ago
David Majda 66de889f4b Implement initializers 14 years ago
David Majda 718bcf5f87 Rename the |action| property of action AST nodes to |code| 14 years ago
David Majda c0f0d56975 Fix incorrect comment 14 years ago
David Majda 8a2e21fa3f Inlined the |initialContext| variable 14 years ago
David Majda 439c815e48 Move lot of stuff in generated parsers into the |parse| method
We want to have the rule parsing functions inside the |parse| method
because we want them to share a common environment. In the future,
initializers will be executed in this enviromnent and thus functions and
variables defined by them will be accessible to the rule parsing
functions.

Moving various private properties from the parser object into the
|parse| method was not strictly necessary, but it was a natural step
after moving the functions.
14 years ago
David Majda 1daf1448e5 Get rid of the |_startRule| property in generated parsers. 14 years ago
David Majda 95735f2c97 Allow trailing semicolon (";") for rules 14 years ago
David Majda 7d4911ec53 Emit little bit less whitespace in actions 14 years ago
David Majda ee8c121676 Use labeled expressions and variables instead of $1, $2, etc.
Labeled expressions lead to more maintainable code and also will allow
certain optimizations (we can ignore results of expressions not passed
to the actions).

This does not speed up the benchmark suite execution statistically
significantly on V8.

Detailed results (benchmark suite totals):

---------------------------------
 Test #     Before       After
---------------------------------
      1   28.43 kB/s   28.46 kB/s
      2   28.38 kB/s   28.56 kB/s
      3   28.22 kB/s   28.58 kB/s
      4   28.76 kB/s   28.55 kB/s
      5   28.57 kB/s   28.48 kB/s
---------------------------------
Average   28.47 kB/s   28.53 kB/s
---------------------------------

Mozilla/5.0 (X11; U; Linux i686; en-US) AppleWebKit/533.4 (KHTML, like Gecko) Chrome/5.0.375.55 Safari/533.4
14 years ago
David Majda 52704593cd Allow labeled expressions in the metagrammar (without any meaning yet) 14 years ago
David Majda 409ddf2ae8 Formatted all grammars more consistently and transparently
This is purely cosmetical change, no functionality was affected
(hopefully).
14 years ago
David Majda 698564a3c2 Replace ":" after a rule name with "="
I'll introduce labelled expressions shortly and I want to use ":" as a
label-expression separator. This change avoids conflict between the two
meanings of ":". (What would e.g. "foo: 'bar'" mean?  Rule "foo"
matching string "bar", or string "bar" labelled "foo"?)
14 years ago
David Majda 7fdf0492c7 Fixed error message for invalid character range + added test 14 years ago
David Majda 570658756a Remove useless action from the metagrammar 14 years ago
David Majda d1fc16c373 Fix bug causing incorrect error messages
The bug could cause the list of expected strings in an error message to
contain strings that shouldn't be there.

Closes #2.
14 years ago
David Majda 90ed4712e9 Add compiler optimization: Remove proxy rules
This shouldn't have measurable effect on the benchmarks as there are no
proxy rules in the grammars the benchamrk uses. However the effect on
generated parsers' speed should be positive generally.
14 years ago
David Majda 33a1a7c1e9 Clean up class handling in the metagrammar and compiler
The class AST node now contains structured data and a raw text which is
used for error messages.
14 years ago
David Majda 137a4b4f53 Renamed |characters| -> |chars| (shorter, no loss of expressivity) 14 years ago
David Majda 4e968892be Guard against redefinition of |undefined|
In most cases, code pattern

  x === undefined

was transformed to

  typeof(x) === "undefined"

and similarly with |!==|.

In the generated code, the condition was simply made less strict to
avoid performance penalty of string comparison (I don't think JavaScript
VMs optimize this specific pattern to avoid it).
14 years ago
David Majda d85bfcb2e9 Fix comment typo 14 years ago
David Majda 76ed63c86e AST refactoring 6/6: Get rid of the |Grammar| namespace 14 years ago
David Majda b4bf49443a AST refactoring 5/6: Make AST classless 14 years ago
David Majda 41abb7ad92 AST refactoring 4/6: Rewrite compilation to not extend the AST nodes 14 years ago
David Majda 5885a34dde AST refactoring 3/6: Rewrite checks to not extend the AST nodes 14 years ago
David Majda c59516541f AST refactoring 2/6: Add |type| property to AST nodes 14 years ago
David Majda 4e99a2bda7 AST refactoring 1/6: Make properties of AST nodes public
Removed undescore prefix of the properties and deleted getters.
14 years ago
David Majda 6f2a188efc Checks refactoring
Changed two things:

  1. Checks are run in |PEG.Compiler.compileParser|, not in
     |PEG.buildParser|.

  2. Checks are extracted into separate functions.
14 years ago
David Majda 85930cbcfe Reorder AST stuff more consistently and sensibly
There is no functional change in this commit.
14 years ago
David Majda f28c52fde2 Rename |_element| to |_expression| in AST
All nodes which have one subexpression store it in the |_expression| property
now.
14 years ago
David Majda 7d1261c0fc Regenerate lib/metagrammar.js (forgot to do it in previous commit) 14 years ago
David Majda cc7f1d96eb Avoid |call| when calling actions with one parameter.
This speeds up the benchmark suite execution by 0.18%, which may just be a
measurement error. (Standrad statistic tests would tell more, but I don't want
to mess with them now.) The code is little bit nicer this way though.

Going further and avoiding |apply| seems to slow thigs down a bit, possibly
because multiple array accesses. I may try improved version without array
accesses (where Action passes the Sequence variable names to save the results
into) sometime later.

Detailed results (benchmark suite totals):

---------------------------------
 Test #     Before       After
---------------------------------
      1   29.08 kB/s   28.91 kB/s
      2   28.72 kB/s   28.75 kB/s
      3   28.78 kB/s   28.88 kB/s
      4   28.57 kB/s   28.90 kB/s
      5   28.84 kB/s   28.81 kB/s
---------------------------------
Average   28.80 kB/s   28.85 kB/s
---------------------------------

Mozilla/5.0 (X11; U; Linux i686; en-US) AppleWebKit/533.2 (KHTML, like Gecko) Chrome/5.0.342.9 Safari/533.2
14 years ago
David Majda e3aa4df090 Changed action parameter processing to avoid the arguments object.
The action now computes the number of passed parameters during the code
generation and the parameters are declared directly as $1, $2, etc. in the
generated function.

This does not speed up the benchmark suite execution statistically significantly
on V8.

Detailed results (benchmark suite totals):

---------------------------------
 Test #     Before       After
---------------------------------
      1   28.68 kB/s   29.08 kB/s
      2   28.77 kB/s   28.72 kB/s
      3   28.89 kB/s   28.78 kB/s
      4   28.84 kB/s   28.57 kB/s
      5   28.86 kB/s   28.84 kB/s
---------------------------------
Average   28.81 kB/s   28.80 kB/s
---------------------------------

Mozilla/5.0 (X11; U; Linux i686; en-US) AppleWebKit/533.2 (KHTML, like Gecko) Chrome/5.0.342.9 Safari/533.2
14 years ago
David Majda a1dcd245bb Action AST node no longer accepts functions as actions (only strings). 14 years ago
David Majda b2f230fad2 Added Optional AST node.
This does not speed up the benchmark suite execution statistically significantly
on V8.

Detailed results (benchmark suite totals):

---------------------------------
 Test #     Before       After
---------------------------------
      1   28.84 kB/s   28.75 kB/s
      2   28.76 kB/s   28.69 kB/s
      3   28.72 kB/s   28.69 kB/s
      4   28.84 kB/s   28.93 kB/s
      5   28.82 kB/s   28.70 kB/s
---------------------------------
Average   28.80 kB/s   28.75 kB/s
---------------------------------

Mozilla/5.0 (X11; U; Linux i686; en-US) AppleWebKit/533.2 (KHTML, like Gecko)
Chrome/5.0.342.9 Safari/533.2
14 years ago
David Majda e5df8284b5 Added AndPredicate AST node.
This does not speed up the benchmark suite execution statistically significantly
on V8.

Detailed results (benchmark suite totals):

---------------------------------
 Test #     Before       After
---------------------------------
      1   28.72 kB/s   28.84 kB/s
      2   28.84 kB/s   28.76 kB/s
      3   28.83 kB/s   28.72 kB/s
      4   28.81 kB/s   28.84 kB/s
      5   28.76 kB/s   28.82 kB/s
---------------------------------
Average   28.79 kB/s   28.80 kB/s
---------------------------------

Mozilla/5.0 (X11; U; Linux i686; en-US) AppleWebKit/533.2 (KHTML, like Gecko) Chrome/5.0.342.9 Safari/533.2
14 years ago
David Majda c3c1c79665 Added OneOrMore AST node.
This speeds up the benchmark suite execution by 1.08% on V8.

Detailed results (benchmark suite totals):

---------------------------------
 Test #     Before       After
---------------------------------
      1   28.38 kB/s   28.72 kB/s
      2   28.52 kB/s   28.84 kB/s
      3   28.41 kB/s   28.83 kB/s
      4   28.47 kB/s   28.81 kB/s
      5   28.64 kB/s   28.76 kB/s
---------------------------------
Average   28.48 kB/s   28.79 kB/s
---------------------------------

Mozilla/5.0 (X11; U; Linux i686; en-US) AppleWebKit/533.2 (KHTML, like Gecko) Chrome/5.0.342.9 Safari/533.2
14 years ago
David Majda 8f59e21c8d Renamed an iterator variable: "key" -> "rule". 14 years ago
David Majda 3f5cb8850c Fixed PEG.buildParser's documentation and added a test. 14 years ago
David Majda 48da65d08e PEG.buildParser now accepts grammars only in string format. 14 years ago
David Majda a86e06a216 Add "Generated by ..." message to the generated parsers. 14 years ago
David Majda 09291d6f0f Use "charAt(...)" instead of "[...]" for accessing string characters (compatibility with IE < 8). 14 years ago
David Majda 4b51e6a6d3 Quote null characters in regexps, IE does not like them. 14 years ago
David Majda 7fc491412d Work around the fact that IE does not recognize "\v" in strings. 14 years ago
David Majda 6abda95a99 Made regexps generated for empty character classes ("[]" and "[^]") work in IE. 14 years ago
David Majda e79e869993 Compensate for IE's lack of Array.prototype.indexOf function. 14 years ago
David Majda e63f64a3d5 Make the generated parsers standalone (no runtime is required).
This and also speeds up the benchmark suite execution by 7.83 % on V8.

Detailed results (benchmark suite totals):

---------------------------------
 Test #     Before       After
---------------------------------
      1   26.17 kB/s   28.16 kB/s
      2   26.05 kB/s   28.16 kB/s
      3   25.99 kB/s   28.10 kB/s
      4   26.13 kB/s   28.11 kB/s
      5   26.14 kB/s   28.07 kB/s
---------------------------------
Average   26.10 kB/s   28.14 kB/s
---------------------------------

Mozilla/5.0 (X11; U; Linux i686; en-US) AppleWebKit/533.2 (KHTML, like Gecko) Chrome/5.0.342.7 Safari/533.2
14 years ago
David Majda 3f85a9ca84 Regenerated the metaparser with one-level rule cache. 14 years ago
David Majda 24d38f74b9 Replaced two-level rule cache with a one-level one.
This leads to simpler code and also speeds up the benchmark suite execution by
5,89 % on V8.

Detailed results (benchmark suite totals):

---------------------------------
 Test #     Before       After
---------------------------------
      1   24,70 kB/s   26,14 kB/s
      2   24,49 kB/s   26,05 kB/s
      3   24,67 kB/s   25,99 kB/s
      4   24,65 kB/s   26,13 kB/s
      5   24,71 kB/s   26,14 kB/s
---------------------------------
Average   24,64 kB/s   26.10 kB/s
---------------------------------

Mozilla/5.0 (X11; U; Linux i686; en-US) AppleWebKit/533.2 (KHTML, like Gecko) Chrome/5.0.342.7 Safari/533.2
14 years ago
David Majda 74830d4f8f Sort expected strings in the error messages. 14 years ago
David Majda 37521cffa5 Error messages now do not contain duplicities. 14 years ago
David Majda 714512f232 Implemented generic AST node extension mechanism. 14 years ago
David Majda 1aa3d8e07e Implemented a nop (no operation) function and used it on few places. 14 years ago
David Majda 16f238a64d Fixed comment heading. 14 years ago
David Majda 3291c70d97 Added \uFEFF (BOM) to the definition of whitespace in the metagrammar.
The Rhino bug that prevented inclusion of \uFEFF among the whitespace characters
is no longer relevant here because we compile character classes into regexps
now, which avoids the infinite recursion.
14 years ago
David Majda 383c5acaa6 Replaced \xA0 by \u00A0 in the whitespace definition in the metagrammar.
This is purely stylistic change.
14 years ago
David Majda 20e230ca0e Killed *MatchFailure classes => simpler code. 14 years ago
David Majda 4f4bb34ded Implemented negative character classes (e.g. [^a-z]). 14 years ago
David Majda 22d2ac8ac2 Rewrote implementation of classes to be regexp-based. 14 years ago
David Majda 56ffa94cc7 PEG.buildParser reports left recursion (both direct and indirect). 14 years ago
David Majda 3a65316416 PEG.buildParser reports missing referenced rules. 14 years ago
David Majda 6bbd88088b Implemented and used PEG.ArrayUtils.each. 14 years ago
David Majda eae48caf91 Regenerated the grammar parser. 14 years ago
David Majda 6f510a0336 The cache does not remember match length but next position after the match.
This leads to simpler and faster code because it avoids one addition and
subtraction.
14 years ago
David Majda 796c98bf8e Changed order of parameters in the SyntaxError constructor to make creating error with unknown location easier. Also fixes bug with reporting of invalid ranges such as [b-a] in the metagrammar. 14 years ago
David Majda 00a258d246 Renamed "humanName" to "displayName". 14 years ago
David Majda a43d1b33e3 Bootstrapped the grammar parser, yay! I should have done this long ago. 14 years ago
David Majda 636ceb2719 Metagrammar recognizes JavaScript-like comments. 14 years ago
David Majda 7bf51eddf0 Removed trailing commas in object initializers (Google Closure does not like them). 14 years ago
David Majda 452243d450 Improved error reporting for predicates a bit. 14 years ago
David Majda 69906e9730 Do not recognize \uFEFF as whitespace in the metagrammar since it does not work with Rhino. 14 years ago
David Majda bddb65ab9b Improved & simplified error handling code. 14 years ago
David Majda b86a219c86 Ensure that the same grammar and start rule always generate exactly the same parser. 14 years ago
David Majda c3dd696a3e Initial commit. 14 years ago