426 Commits (b81396a904fef4992ecd9fdc2b77a0226e2d7ee4)

Author SHA1 Message Date
David Majda d2569b9bf3 Don't use "objects" in lib/compiler/passes/generate-js.js
The "objects" module will be removed.

See #442.
8 years ago
David Majda 8a75d19468 Don't use "objects" in lib/compiler/passes/generate-bytecode.js
The "objects" module will be removed.

See #442.
8 years ago
David Majda 97d92c9d8b Don't use "objects" in lib/compiler/index.js
The "objects" module will be removed.

See #442.
8 years ago
David Majda c344460855 Remove now unused lib/utils/arrays.js
See #442.
8 years ago
David Majda f81ae1845b Don't use "arrays" in lib/compiler/passes/report-infinite-recursion.js
The "arrays" module will be removed.

See #442.
8 years ago
David Majda 71ef4c9b91 Don't use "arrays" in lib/compiler/passes/remove-proxy-rules.js
The "arrays" module will be removed.

See #442.
8 years ago
David Majda 8f8484b1a1 Don't use "arrays" in lib/compiler/passes/generate-js.js
The "arrays" module will be removed.

See #442.
8 years ago
David Majda 33f23ee4be Don't use "arrays" in lib/compiler/passes/generate-bytecode.js
The "arrays" module will be removed.

See #442.
8 years ago
David Majda 4dec5e52ba Don't use "arrays" in lib/compiler/asts.js
The "arrays" module will be removed.

See #442.
8 years ago
David Majda 5822596ab8 Replace classes.subclass with native classes
See #442.
8 years ago
David Majda 6fa8ad63f9 Replace some functions with arrow functions
Because arrow functions work rather differently than normal functions (a
bad design mistake if you ask me), I decided to be conservative with the
conversion.

I converted:

  * event handlers
  * callbacks
  * arguments to Array.prototype.map & co.
  * small standalone lambda functions

I didn't convert:

  * functions assigned to object literal properties (the new shorthand
    syntax would be better here)
  * functions passed to "describe", "it", etc. in specs (because Jasmine
    relies on dynamic "this")

See #442.
8 years ago
David Majda d00e9526c3 Minimize variable scope
Where possible, move "let" statements into inner blocks, loop headers,
etc.

See #442.
8 years ago
David Majda bdf91b5941 Replace "var" with "let" & "const"
This is purely a mechanical change, not taking advantage of block scope
of "let" and "const". Minimizing variable scope will come in the next
commit.

In general, "var" is converted into "let" and "const" is used only for
immutable variables of permanent character (generally spelled in
ALL_CAPS). Using it for any immutable variable regardless on its
permanence would feel confusing.

Any code which is not transpiled and needs to run in ES6 environment
(examples, code in grammars embedded in specs, ...) is kept unchanged.
This is also true for code generated by PEG.js.

See #442.
8 years ago
David Majda c3e7072fa2 Remove unused arrays.pluck function 8 years ago
David Majda 062c6ae706 Escape backspace in regexp classes as "\b", not "\x08"
The "\x08" escaping is necessary only outside of classes (where "\b"
means "word boundary").
8 years ago
David Majda bd62ddf846 Use "[]" & "[^]" for empty character classes, not "(?!)" & "[\\S\\s]"
See #441.
8 years ago
David Majda 9c04c94c85 Escape vertical tab as "\v", not "\x0B"
See #441.
8 years ago
David Majda f36a667376 Remove "undefined" redefinition protection
See #441.
8 years ago
David Majda fad4ab74d1 Replace suitable for loops with Array methods (in /lib)
See #441.
8 years ago
David Majda 3e8bcbea73 Replace suitable for loops with Array methods (in /src)
See #441.
8 years ago
David Majda 1c3fbf6cb0 Replace "... instanceof Array" with "Array.isArray(...)"
See #441.
8 years ago
David Majda d346d2a66d Replace objects.keys with Object.keys
See #441.
8 years ago
David Majda 0059cc3bdd Replace arrays.some with Array.prototype.some
See #441.
8 years ago
David Majda d162fe1cfc Replace arrays.every with Array.prototype.every
See #441.
8 years ago
David Majda 5f65de92bc Replace arrays.map with Array.prototype.map
See #441.
8 years ago
David Majda b044a021c4 Replace arrays.each with Array.prototype.forEach
See #441.
8 years ago
David Majda 671166bbe8 Update version to 0.10.0 8 years ago
David Majda 8003edafc9 Rename the "node" module format to "commonjs"
Parsers generated in this format use module.exports, so they are not
strictly CommonJS, but this is a common extension and the original name
would be confusing once Node.js implements ES2015 modules.
8 years ago
David Majda 8962dcfd16 Rename the "global" module format to "globals"
I think the new name is more widely used when describing the pattern.
8 years ago
David Majda b77d33ca05 generate-js.js: Quote the "class" key in DESCRIBE_EXPECTATION_FNS
"class" is a reserved word. Having it as a key unquoted broke IE 8 (both
in standards and quirks mode) and IE 9 (in quirks mode).
8 years ago
David Majda 67d85f2de8 Align names of compiler passes that detect infinite loops
Rename compiler passes as follows:

  reportLeftRecursion -> reportInfiniteRecursion
  reportInfiniteLoops -> reportInfiniteRepetition

This reflects the fact that both passes detect different ways of causing
the same problem (possible infinite loop when parsing).
8 years ago
David Majda 9717dc3417 Talk about "undefined rules" instead of "missing rules" internally
The new terminology is more precise and in line with commonly used
programming languages.

The change involves mainly renaming related compiler pass and files
associated with it.
8 years ago
David Majda e9cb23608d Split peg$buildException into two separate functions
This change reflects the fact that PEG.js-generated parsers really
produce two kinds of syntax errors:

  Structured errors

    Caused by match failures, trailing input, or calls of the "expected"
    function in parser code. Their messages have fixed format ("Expected
    ... but ... found.").

  Simple errors

    Caused by calls of the "error" function in parser code. Their
    messages don't have any fixed format.

Each kind of error now has a separate helper function which builds its
instances.
8 years ago
David Majda e03d92488a Set the "found" property of syntax errors produced by "error" to null
The property doesn't correspond to anything in the error's message.
8 years ago
David Majda 6ca546a44e Regenerate lib/parser.js 8 years ago
David Majda db9920e3ca peg.generate: Implement { format: "global" } 8 years ago
David Majda 61c11ee1b4 peg.generate: Implement { format: "amd" } 8 years ago
David Majda f633f697c9 peg.generate: Implement { format: "node" } 8 years ago
David Majda 9454c11c59 generate-js.js: Fix "=" alignment 8 years ago
David Majda e546af5543 Regenerate lib/parser.js 8 years ago
David Majda e8be76ee3a Don't expose the "parser" variable in parser code
The "parser" variable allowed access to the parser object. Among other
things, this made it possible to invoke the parser recursively using
"parser.parse".

One problem with the "parser" variable is that it bakes in the idea that
the parser is an *object*, not a *module*. While this is true now, it
won't necessarily be in the future, when parsers may be exported as ES6
modules. Also, people tend to use parsers as modules even today, e.g.
like this:

  var parse = require("parser").parse;
  var result = parse(...);

Such usage broke the "parser" variable (as it was implemented).

For this reasons I decided to remove the "parser" variable. If someone
needs to do tricks like recursive invocation of the parser, he/she must
pass the parser or the "parse" function itself using options.

Related to #433.
8 years ago
David Majda 6aa956452e Don't use "this" inside peg.generate
This change makes it possible to use "generate" as a module function,
e.g. like this:

  var generate = require("pegjs").generate;
  var parser = generate(...);

Fixes #433.
8 years ago
David Majda 65550965c6 Remove extraneous "with" from an error message 8 years ago
David Majda b3a90de020 Syntax error messages: Use Oxford comma
In general PEG.js uses American English, where Oxford comma is
prevalent.

Part of #371.
8 years ago
David Majda ec8ede5bbe Grammar error messages 3/3: Improve the left recursion message
New wording is more explanatory.

Part of #371.
8 years ago
David Majda f5e43f842c Grammar error messages 2/3: Improve the infinite loop message
New wording is more explanatory.

Part of #371.
8 years ago
David Majda 85fb8aaa0e Grammar error messages 1/3: Improve the missing rule message
New wording is more similar to wording used in various programming
languages and it is in line with the duplicate rule message.

Part of #371.
8 years ago
David Majda eb67cbedb4 Report duplicate labels as errors
Resolves #270.
8 years ago
David Majda 2a889535bd Add location to the "Rule ... is already defined" error message
See this discussion:

  eb5875bc6a (commitcomment-17970220)
8 years ago
David Majda eb5875bc6a Report duplicate rule definitions as errors
Based on a pull request by Futago-za Ryuu (@futagoza):

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

Resolves #318.
8 years ago
David Majda 149c829897 lib/compiler/index.js: Order default option values alphabetically 8 years ago
David Majda 930877c3ba Move lib/compiler.js to lib/compiler/index.js
This makes "compiler" a regular Node.js module.
8 years ago
David Majda 5a4d04fa90 Construct expectations using functions
Until now, expectations were constructed using object literals. This
commit changes the construction to use factory functions.

This change makes generated parsers slightly smaller because property
names don't have to be repeated many times and factory function calls
are more amenable to minifying.

Some numbers based on the aggregate size of parsers generated from
examples/*.pegjs:

  Optimization   Minified?   Size before   Size after   Saving
  ------------------------------------------------------------
  speed          no               719066       716063    0.42%
  speed          yes              188998       180202    4.65%
  size           no               194810       197813    1.52%
  size           yes              108782        99947    8.12%

(Minification was done using "uglify --mangle --compress" with
uglify-js 2.4.24.)
8 years ago
David Majda e7d03825e0 AST: Remove the "rawText" property from "class" nodes
It isn't used anymore.
8 years ago
David Majda 35c8280743 Expectation refactoring 7/7: Regenerate lib/parser.js 8 years ago
David Majda 8639cf6d61 Expectation refactoring 6/7: Move "buildMessage" to SyntaxError
The "buildMessage" utility function, which was previously internal, is
now exposed as SyntaxError.buildMessage in generated parsers.

The motivation behind this is two-fold:

  1. Building of a syntax error message is a responsibility of the
     SyntaxError class, meaning the code should be placed there.

  2. By exposing the message building code, parser users can use it to
     generate customized error messages without duplicating PEG.js's code.

Note that helper functions inside "buildMessage" ("describeExpected",
"describeFound", etc.) currently aren't exposed. They may become exposed
in the future if there is enough demand.
8 years ago
David Majda 999cc7be74 Expectation refactoring 5/7: Refactor "buildMesage"
Mostly just extract few functions, increasing readability.
8 years ago
David Majda 319931876d Expectation refactoring 4/7: Generate descriptions dynamically
Instead of pre-generating expectation descriptions when generating
parsers, generate them dynamically from structured information contained
in the expectations.

This change makes descriptions a presentation-only concept. It also
makes generated parsers smaller.
8 years ago
David Majda 22cb123479 Expectation refactoring 3/7: Change expectation processing
Before this commit, expectations were sorted and de-duplicated before
they were passed to "buildMessage" and exposed in the "expected"
property of syntax errors. This commit moves this processing into
"buildMessage" and rewrites it to process only expectation descriptions.
This means expectations exposed in the "expected" property are "raw"
(not sorted and de-duplicated).

This change will allow us to get rid of the "description" property of
expectations and compute descriptions dynamically from structured
information in the expectations. This will make descriptions a
presentation-only concept. It will also make generated parsers smaller.

Note that to keep expectations in the "expected" property sorted even
without the "description" property, some sorting scheme based on
structured information in the expectations would have to be devised,
which would complicate things with only a little benefit. Therefore I
chose to keep the expectations there "raw".
8 years ago
David Majda c6e8c53f1b Expectation refactoring 2/7: Restructure "class" expectations
Changes:

  * Remove the "value" property (it is replaced by other properties).

  * Add the "parts", "inverted", and "ignoreCase" properties (which
    allow more structured access to expectation data).
8 years ago
David Majda eda2a34c7f Expectation refactoring 1/7: Restructure "literal" expectations
Changes:

  * Rename the "value" property to "text" (because it doesn't contain
    the whole value, which also includes the case sensitivity flag).

  * Add the "ignoreCase" property (which was missing).
8 years ago
David Majda d48983dd6a Don't use the "i" suffix for case-insensitive class descriptions
If the described class is case-sensitive, nothing changes.

If the described class is case-insensitive, its description doesn't
indicate that anymore. The indication was awkward and it was meaningful
only for parser users familiar with PEG.js grammar syntax (typically a
minority). For cases where case insensitivity indication is vital, named
rules can be used to customize the reporting.

Note that literal descriptions already ignore the case-sensitivity flag;
this commit only makes things consistent.
8 years ago
David Majda b2d7f9e02f Fix comment typo 8 years ago
David Majda d73a5208a0 Simplify various escaping functions
Simplify regexps that specify ranges of characters to escape with "\xXX"
and "\uXXXX" in various escaping functions. Until now, these regexps
were (mostly) mutually exclusive with more selective regexps applied
before them, but this became a maintenance headache. I decided to
abandon the exclusivity, which allowed to simplify these regexps (at the
cost of introducing an ordering dependency).
8 years ago
David Majda b31436d778 Escape also DEL (U+007F) when generating JavaScript strings & regexps
It is a control character.
8 years ago
David Majda 1f7efd57c0 Remove various JSHint-related cruft
We use ESLint now, which is smarter about some things.
8 years ago
David Majda 75cedcb7d8 Harmonize found string escaping with expectation escaping
Change how found strings are escaped when building syntax error
messages:

  * Do not escape non-ASCII characters (U+0100-U+FFFF). They are
    typically more readable in their raw form.

  * Escape DEL (U+007F). It is a control character.

  * Escape NUL (U+0000) as "\0", not "\x00".

  * Do not use less known shortcut escape sequences ("\b", "\f"), only the
    well-known ones ("\0", "\t", "\n", "\r").

These changes mirror expectation escaping changes done in
4fe682794d.

Part of work on #428.
8 years ago
David Majda 6b60896216 Revert "Remove info about found string from syntax errors"
This reverts commit 25ab98027d.

Part of work on #428.
8 years ago
David Majda 4fe682794d Improve expression descriptions in error messages
Before this commit, descriptions of literals used in error messages were
built by applying JavaScript string escaping to their values, making the
descriptions look like JavaScript strings. Descriptions of character
classes were built using their raw text. These approaches were mutually
inconsistent and lead to descriptions which were over-escaped and not
necessarily human-friendly (in case of literals) or coupled with details
of the grammar (in case of character classes).

This commit changes description building code in both cases and unifies
it. The intent is to generate human-friendly descriptions of matched
expressions which are clean, unambiguous, and which don't escape too
many characters, while handling special characters such as newlines
well.

Fixes #127.
8 years ago
David Majda 2fd77b96fc Revert "Use literal raw text in error messages"
I no longer think that using raw literal texts in error messages is the
right thing to do. The main reason is that it couples error messages
with details of the grammar such as use of single or double quotes in
literals. A better solution is coming in the next commit.

This reverts commit 69a0f769fc.
8 years ago
David Majda f4504a93fe Rename the "buildParser" function to "generate"
In most places, we talk about "generating a parser", not "building a
parser", which the function name should reflect. Also, mentioning a
parser in the name is not necessary as in case of a parser generator
it's pretty clear what is generated.
8 years ago
David Majda 0847a69643 Rename the "PEG" variable to "peg"
So far, PEG.js was exported in a "PEG" global variable when no module
loader was detected. The same variable name was also conventionally used
when requiring it in Node.js or otherwise referring to it. This was
reflected in various places in the code, documentation, examples, etc.

This commit changes the variable name to "peg" and fixes all relevant
occurrences. The main reason for the change is that in Node.js, modules
are generally referred to by lower-case variable names, so "PEG" was
sticking out when used in Node.js projects.
8 years ago
David Majda 057a93fbc7 Move the "Generated by ..." comment out of wrapping functions
The wrapping functions are also generated by PEG.js, so the comment
should be above them to mark them as such. This shouldn't cause any
problems technically.
8 years ago
David Majda f934199fba Simplify code which generates parser wrappers 8 years ago
David Majda 810567d865 UMD parsers: Allow specifying parser dependencies
Introduce two ways of specifying parser dependencies: the "dependencies"
option of PEG.buildParser and the -d/--dependency CLI option. Specified
dependencies are translated into AMD dependencies and Node.js's
"require" calls when generating an UMD parser.

Part of work on #362.
8 years ago
David Majda fe6ce38d08 UMD parsers: Regenerate lib/parser.js
Part of work on #362.
8 years ago
David Majda b87268ade6 UMD parsers: Allow generating parsers in UMD format from the API
Introduce new "format" and "exportVar" options to PEG.buildParser which
together allow generating parsers in UMD format.

Part of work on #362.
8 years ago
David Majda ab0e85b006 UMD parsers: Refactor "generateWrapper"
Extract "generateWrapper" code which generates code of the intro and the
returned parser object into helper functions. This is pure refactoring,
generated parser code is exactly the same as before.

This change will make it easier to modifiy "generateWrapper" to produce
UMD modules.

Part of work on #362.
8 years ago
David Majda 7f8b3f7012 UMD parsers: Generate parser wrapper separately from its toplevel code
Code which was at the toplevel of the "generateJS" function in the code
generator is now split into "generateToplevel" (which genreates parser
toplevel code) and "generateWrapper" (which generates a wrapper around
it). This is pure refactoring, generated parser code is exactly the same
as before.

This change will make it easier to modifiy the code genreator to produce
UMD modules.

Part of work on #362.
8 years ago
David Majda 5e702b5901 lib/compiler.js: Fix indentation 8 years ago
David Majda ce44c62f14 Support passing custom location info to "error" and "expected"
Based on a pull request by Konstantin (@YemSalat):

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

Resolves #390.
8 years ago
David Majda da2378d887 Rewrite handling of optional parameters
Instead of testing arguments.length to see whether an optional parameter
was passed to a function, compare its value to "undefined". This
approach has two advantages:

  * It is in line with handling of default parameters in ES6.

  * Optional parameters are actually spelled out in the parameter
    list.

There is also one important disadvantage, namely that it's impossible to
pass "undefined" as an optional parameter value. This required a small
change in two tests.

Additional notes:

  * Default parameter values are set in assignments immediately
    after the function header. This reflects the fact that these
    assignments really belong to the parameter list (which is where they
    are in ES6).

  * Parameter values are checked against "void 0" in places where
    "undefined" can potentially be redefiend.
8 years ago
David Majda 0c39f1cf86 Fix labels leaking to outer scope
Labels in expressions like "(a:"a")" or "(a:"a" b:"b" c:"c")" were
visible to the outside despite being wrapped in parens. This commit
makes them invisible, as they should be.

Note this required introduction of a new "group" AST node, whose purpose
is purely to provide label scope isolation. This was necessary because
"label" and "sequence" nodes don't (and can't!) provide this isolation
themselves.

Part of a fix of #396.
8 years ago
David Majda 88f1d1369b Detect newlines using charCodeAt instead of charCode
In generated parsers, detect newlines using charCodeAt instead of
charCode. This should be slightly faster.
8 years ago
David Majda 18d266be67 Remove support for newlines other than "\n" and "\r\n"
Before this commit, generated parsers considered the following character
sequences as newlines:

  Sequence   Description
  ------------------------------
  "\n"       Unix
  "\r"       Old Mac
  "\r\n"     Windows
  "\u2028"   line separator
  "\u2029"   paragraph separator

This commit limits the sequences only to "\n" and "\r\n". The reason is
that nobody uses Unicode newlines or "\r" in practice.

A positive side effect of the change is that newline-handling code
became simpler (and likely faster).
8 years ago
David Majda e61c23c634 ESLint: Set environments better
Instead of setting ESLint environment to "node" globally, set it on
per-directory basis using separate .eslintrc.json files:

  Directory   Environment
  -----------------------
  bin         node
  lib         commonjs
  spec        jasmine

It was impossible to use this approach for the "benchmark" directory
which contains a mix of files used in various environments. For
benchmark/run, the environment is set inline. For the other files, as
well as spec/helpers.js, the globals are declared manually (it is
impossible to express how these files are used just by a list of
environments).

Fixes #408.
8 years ago
David Majda ddd4ac3787 Fix ESLint errors in lib/parser.js
Fix the following errors:

    31:9   error  "parser" is defined but never used    no-unused-vars
   406:14  error  "expected" is defined but never used  no-unused-vars
  1304:15  error  "s1" is defined but never used        no-unused-vars
  1386:15  error  "s1" is defined but never used        no-unused-vars
  1442:15  error  "s1" is defined but never used        no-unused-vars
8 years ago
David Majda 88c957c9e8 Fix ESLint errors in lib/compiler/passes/generate-js.js
Fix the following errors:

   65:11  error  Unexpected trailing comma  comma-dangle
  211:40  error  Unexpected trailing comma  comma-dangle
  223:27  error  Unexpected trailing comma  comma-dangle
  233:27  error  Unexpected trailing comma  comma-dangle
8 years ago
David Majda 475215aa52 Expose the AST node visitor builder via PEG.compiler.visitor
This is useful mainly for plugins which manipulate the AST.
9 years ago
David Majda d34faba59e Speed up deduplication of expectations
The expectation deduplication algorithm called |Array.prototype.splice|
to eliminate each individual duplication, which was slow. This caused
problems with grammar/input combinations that generated a lot of
expecations (see #377 for an example).

This commit replaces the algorithm with much faster one, eliminating the
problem.
9 years ago
David Majda a4a66a2e5b Switch from first/rest to head/tail in the PEG.js grammar
In the past year I worked on various grammars where first/rest or
head/tail were used as labels for parts of lists. I found I associate
head/tail with a list immediately, while in case of first/rest I have to
"parse" grammar rules for a while before understanding their structure.

Moreover, I tend to assume that rest is a list of the same thigs as
first, but I don't have such assumption in case of head/tail. This
assumption was in conflict with the grammar structure.

I'm not sure how much these observations are applicable to others, but I
decided to act on them and switch from first/rest to head/tail.
9 years ago
David Majda 69a0f769fc Use literal raw text in error messages
Fixes #127.
9 years ago
David Majda 25ab98027d Remove info about found string from syntax errors
The |found| property wasn't very useful as it mostly contained just one
character or |null| (the exception being syntax errors triggered by
|error| or |expected|). Similarly, the "but XXX found" part of the error
message (based on the |found| property) wasn't much useful and was
redundant in presence of location info.

For these reasons, this commit removes the |found| property and
corresponding part of the error message from syntax errors. It also
modifies error location info slightly to cover a range of 0 characters,
not 1 character (except when the error is triggered by |error| or
|expected|). This corresponds more precisely to the actual situation.

Fixes #372.
9 years ago
David Majda bbb4f006cd Report full rule chain in recursive rule errors
The idea came from a PR by @Mingun:

  https://github.com/pegjs/pegjs/pull/307
9 years ago
David Majda 491106c347 Report left recursion and infinite loops only as "possible"
A semantic predicate can prevent the parser to actually enter infinite
recursion or loop. This is undetectable at compile-time.
9 years ago
David Majda ebf5d969b2 s/alwaysAdvancesOnSuccess/alwaysConsumesOnSuccess/
Matches terminology change from the previous commit.
9 years ago
David Majda 48fe4d6580 Rename generate-javascript.js to generate-js.js
Short & sweet.
9 years ago
David Majda 575883586f Rename javascript.js to js.js
Short & sweet.
9 years ago
David Majda 20a4fb2e7f Update version to 0.9.0 9 years ago
David Majda 671c22e80f Avoid using |console| in default tracer and its tests when not defined
This makes default tracer and its tests work in IE 8-10.
9 years ago
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