A number of improvements to the parser.

Reviewed by me.
This commit is contained in:
Francisco Ryan Tolmasky I committed 2008-11-14 17:56:04 -08:00
1 parent 4dbfe1f23e
commit 26333c3d2b
1 file changed
+221 -211
+221 -211
View File
@@ -67,7 +67,11 @@ var TOKEN_ACCESSORS = "accessors",
TOKEN_CLOSE_BRACKET = ']',
TOKEN_QUESTION_MARK = '?',
TOKEN_OPEN_PARENTHESIS = '(',
TOKEN_CLOSE_PARENTHESIS = ')';
TOKEN_CLOSE_PARENTHESIS = ')',
TOKEN_WHITESPACE = /^(?:(?:\s+$)|(?:\/(?:\/|\*)))/,
TOKEN_NUMBER = /^[+-]?\d+(([.]\d+)*([eE][+-]?\d+))?$/,
TOKEN_IDENTIFIER = /^[a-zA-Z_$](\w|$)*$/;
#define IS_WORD(token) /^\w+$/.test(token)
@@ -81,15 +85,40 @@ var OBJJ_CURRENT_BUNDLE = NULL;
// FIXME: Used fixed regex
var objj_lexer = function(aString)
{
this._index = 0;
this._tokens = (aString + '\n').match(/\/\/.*(\r|\n)?|\/\*(?:.|\n|\r)*?\*\/|\w+\b|[+-]?\d+(([.]\d+)*([eE][+-]?\d+))?|"([^"\\]|\\[\s\S])*"|'[^'\\]*(\\.[^'\\]*)*'|\s+|./g);
this._index = -1;
this._tokens = (aString + '\n').match(/\/\/.*(\r|\n)?|\/\*(?:.|\n|\r)*?\*\/|\w+\b|[+-]?\d+(([.]\d+)*([eE][+-]?\d+))?|"[^"\\]*(\\[\s\S][^"\\]*)*"|'[^'\\]*(\\[\s\S][^'\\]*)*'|\s+|./g);
this._context = [];
return this;
}
objj_lexer.prototype.push = function()
{
this._context.push(this._index);
}
objj_lexer.prototype.pop = function()
{
this._index = this._context.pop();
}
objj_lexer.prototype.peak = function(shouldSkipWhitespace)
{
if (shouldSkipWhitespace)
{
this.push();
var token = this.skip_whitespace();
this.pop();
return token;
}
return this._tokens[this._index + 1];
}
objj_lexer.prototype.next = function()
{
return this._tokens[this._index++];
return this._tokens[++this._index];
}
objj_lexer.prototype.previous = function()
@@ -99,16 +128,20 @@ objj_lexer.prototype.previous = function()
objj_lexer.prototype.last = function()
{
if (this._index > 1)
return this._tokens[this._index - 2];
if (this._index < 0)
return NULL;
return NULL;
return this._tokens[this._index - 1];
}
objj_lexer.prototype.skip_whitespace= function()
objj_lexer.prototype.skip_whitespace= function(shouldMoveBackwards)
{
var token;
while((token = this.next()) && (!(/\S/).test(token) || token.substr(0,2) == "//" || token.substr(0,2) == "/*")) ;
if (shouldMoveBackwards)
while((token = this.previous()) && TOKEN_WHITESPACE.test(token)) ;
else
while((token = this.next()) && TOKEN_WHITESPACE.test(token)) ;
return token;
}
@@ -146,6 +179,7 @@ var objj_preprocessor = function(aString, aSourceFile, aBundle, flags)
this._bundle = aBundle;
this.preprocess(this._tokens, this._preprocessed);
//alert(this._preprocessed + "");
this.fragment();
}
@@ -204,208 +238,61 @@ objj_preprocessor.prototype.accessors = function(tokens)
return attributes;
}
objj_preprocessor.prototype.brackets = function(tokens, /*objj_stringBuffer*/ aStringBuffer)
objj_preprocessor.prototype.brackets = function(/*objj_lexer*/ tokens, /*objj_stringBuffer*/ aStringBuffer)
{
var buffer = aStringBuffer ? aStringBuffer : new objj_stringBuffer();
// We maintain two parallel interpretations through the process,
// One which assumes the brackets form a literal array, and
// another that builds the possible message dispatch composed of
// a receiver, a selector, and a number of marg_list.
var literal = new objj_stringBuffer(),
msgSend = "objj_msgSend",
receiver = "",
selector = "",
marg_list = [];
CONCAT(literal, '[');
// We keep track of the current iterative token, the previous
// expression, tertiary operations, and parenthesis.
var token = "",
array = false,
previous = "",
var tuples = [];
braces = 0,
tertiary = 0,
parenthesis = 0;
while((token = tokens.skip_whitespace()) && token != TOKEN_CLOSE_BRACKET)
{
// We should attempt to preprocess our message code only if we are
// not within parenthesis or a tertiary statement.
var preprocess = !braces && !tertiary && !parenthesis && !array;
// We handle the special case where the receiver is super. In this case,
// use an objj_super object and use objj_msgSendSuper instead of objj_msgSend.
if (token == TOKEN_SUPER)
{
if (!receiver.length)
{
msgSend = "objj_msgSendSuper";
token = "{ receiver:self, super_class:" + this._currentSuperClass + " }";
}
else
objj_exception_throw(new objj_exception(OBJJParseException, "*** Can't use 'super' in this context."));
}
else if (token == TOKEN_OPEN_BRACE)
++braces;
else if (token == TOKEN_CLOSE_BRACE)
--braces;
// Tertiary expressions have the potential to confuse the preprocessor,
// so keep track of them to avoid misidentifying a colon (':') for an
// argument.
else if(token == TOKEN_QUESTION_MARK)
++tertiary;
// Keep track of expressions within parenthesis.
else if(token == TOKEN_OPEN_PARENTHESIS)
++parenthesis;
else if(token == TOKEN_CLOSE_PARENTHESIS)
--parenthesis;
// If we reach a nested bracket, preprocess it first and interpret
// the result as the current token.
else if(token == TOKEN_OPEN_BRACKET)
token = this.brackets(tokens);
else if(token == TOKEN_PREPROCESSOR)
token = this.directive(tokens);
// Preprocess tokens only if we're not within parenthesis or in a
// tertiary statement.
if (preprocess)
{
// If we ever reach a comma that is not in a sub expression,
// and we haven't yet begun to construct a selector, then
// we can be sure that this is not a message dispatch, and
// we should simply return so that the lexer can continue
// to preprocess normally.
if(token == TOKEN_COMMA && !selector.length)
array = true;//return literal + token;
// A colon (':') alerts us that we've reached the end of a label.
if(token == TOKEN_COLON)
{
// If the previous token was actually white space, so this
// is an empty label.
var last = tokens.last();
if (last && (!(/\S/).test(last) || last.substr(0, 2) == "//" || last.substr(0, 2) == "/*"))
{
selector += ':';
marg_list[marg_list.length - 1] += previous;
marg_list[marg_list.length] = previous = "";
}
// If not the previous token was was part of the label and
// thus should be appended to the selector.
else
{
selector += previous + ":";
marg_list[marg_list.length] = previous = "";
}
}
else
{
// Generally we are unconcerned with whitespace, however the new
// operator requires it.
if (previous == TOKEN_NEW)
previous = "new ";
// If we've already begun building our selector, then the token
// should be applied to the current argument.
if (selector.length)
marg_list[marg_list.length - 1] += previous;
// If not, then it belongs to the receiver.
else
receiver += previous;
previous = token.toString();
}
}
// If not, add it to previous to be interpreted as one block.
else
{
// We know this colon (':') to match a previous tertiary expression.
// FIXME PARSER_BUG: This does not properly account for interspersed { } and ?:
// https://trac.280north.com/ticket/15
if(token == TOKEN_COLON && !braces)
--tertiary;
previous += token;
}
// The literal interpretation is always handled in the same
// manner, simply aggregate the tokens, unless we have a new token,
// in which case we need to add back the whitespace we removed.
if (token == TOKEN_NEW)
CONCAT(literal, "new ");
else
CONCAT(literal, token);
}
while (this.preprocess(tokens, NULL, NULL, NULL, tuples[tuples.length] = [])) ;
// If we have a selector, then add the remaining string to the argument.
if (selector.length)
marg_list[marg_list.length - 1] += previous;
if (tuples[0].length === 1)
{
CONCAT(aStringBuffer, '[');
// When we have an empty array literal ([]), tuples[0][0] will be an empty objj_stringBuffer
CONCAT(aStringBuffer, tuples[0][0]);
CONCAT(aStringBuffer, ']');
}
// If not, check whether the final character of our proposed receiver
// is an operator or the new keyword. Also check that the previous
// expression does not begin with a parenthesis, since this means it
// definitely can't be a selector.
// FIXME: There is probably a more concise and efficient way to represent
// these regular expressions.
// FIXME: Should the second expression be the same as the first. For example,
// array[i%] becomes arrayobjj_msgSend(i,"%") if not. This is an error either
// way though. https://trac.280north.com/ticket/6
else if(!array && receiver.length && !((/[\:\+\-\*\/\=\<\>\&\|\!\.\%]/).test(receiver.charAt(receiver.length - 1))) &&
receiver != TOKEN_NEW && !(/[\+\-\*\/\=\<\>\&\|\!\.\[\^\(]/).test(previous.charAt(0)))
selector = previous;
// If we did not build a selector through the parsing process, then we
// are either a single entry literal array, or an array index, and so
// we should simply return our literal string.
else
{
CONCAT(buffer, literal);
CONCAT(buffer, ']');
// Return no matter what!
if (!aStringBuffer)
return buffer;
var selector = new objj_stringBuffer();
//alert(tuples[0][0].toString() + "]" );
// The first two arguments are always the receiver and the selector.
if (tuples[0][0].atoms[0] == TOKEN_SUPER)
{
CONCAT(aStringBuffer, "objj_msgSendSuper(");
CONCAT(aStringBuffer, "{ receiver:self, super_class:" + this._currentSuperClass + " }");
}
else
return;
{
CONCAT(aStringBuffer, "objj_msgSend(");
CONCAT(aStringBuffer, tuples[0][0]);
}
CONCAT(selector, tuples[0][1]);
var index = 1,
count = tuples.length,
marg_list = new objj_stringBuffer();
for(; index < count; ++index)
{
var pair = tuples[index];
CONCAT(selector, pair[1])
CONCAT(marg_list, ", " + pair[0]);
}
CONCAT(aStringBuffer, ", \"");
CONCAT(aStringBuffer, selector); // FIXME: sel_getUid(selector + "") ?
CONCAT(aStringBuffer, '\"');
CONCAT(aStringBuffer, marg_list);
CONCAT(aStringBuffer, ')');
}
// NOTE: For now, turn this behavior off.
// Classes act much like keywords since they are not directly manipulatable.
// We thus check whether it exists in our class hash or working hash, and if
// instead use a reference to it if it does.
// if (tokens.containsClass(receiver) || objj_getClass(receiver)) receiver = "objj_getClass(\"" + receiver + "\")";
// The first two arguments are always the receiver and the selector.
CONCAT(buffer, msgSend);
CONCAT(buffer, '(' + receiver + ", \"" + sel_getUid(selector) + "\"");
// Populate the remaining parameters with the provided arguments.
var index = 0,
count = marg_list.length;
for(; index < count; ++index)
CONCAT(buffer, ", " + marg_list[index]);
// Return the fully preprocessed message dispatch.
CONCAT(buffer, ')');
if (!aStringBuffer)
return buffer;
}
objj_preprocessor.prototype.directive = function(tokens, aStringBuffer, allowedDirectivesFlags)
{
// Grab the next token, preprocessor directives follow '@' immediately.
@@ -503,7 +390,7 @@ objj_preprocessor.prototype.implementation = function(tokens, /*objj_stringBuffe
{
token = tokens.skip_whitespace();
if (!(/^[a-zA-Z_$](\w|$)*$/).test(token))
if (!TOKEN_IDENTIFIER.test(token))
objj_exception_throw(new objj_exception(OBJJParseException, "*** Expected class name, found \"" + token + "\"."));
superclass_name = token;
@@ -758,14 +645,130 @@ objj_preprocessor.prototype.method = function(tokens)
return buffer;
}
objj_preprocessor.prototype.preprocess = function(tokens, /*objj_stringBuffer*/ aStringBuffer, terminator, instigator)
objj_preprocessor.prototype.preprocess = function(tokens, /*objj_stringBuffer*/ aStringBuffer, terminator, instigator, tuple)
{
var buffer = aStringBuffer ? aStringBuffer : new objj_stringBuffer(),
count = 0,
token = "";
while((token = tokens.next()) && ((token != terminator) || count))
if (tuple)
{
tuple[0] = buffer;
var bracket = false,
closures = [0, 0, 0];
}
while ((token = tokens.next()) && ((token != terminator) || count))
{
if (tuple)
{
// Ignore :'s the belong to tertiary operators (?:)
if (token === TOKEN_QUESTION_MARK)
++closures[2];
// Ingore anything between { } and ()
else if (token === TOKEN_OPEN_BRACE)
++closures[0];
else if (token === TOKEN_CLOSE_BRACE)
--closures[0];
else if (token === TOKEN_OPEN_PARENTHESIS)
++closures[1];
else if (token === TOKEN_CLOSE_PARENTHESIS)
--closures[1];
// If not in {} and not in () and this is a colon and we don't belong to a tertiary operator OR this is a closing bracket...
else if ((token === TOKEN_COLON && closures[2]-- === 0 ||
(bracket = (token === TOKEN_CLOSE_BRACKET))) &&
closures[0] === 0 && closures[1] === 0)
{
tokens.push(); // 1
// If a bracket made us enter, go backwards skipping whitespace ([a b ] allowed),
// if not grab token immediately behind us ([a b : c] not allowed
var label = bracket ? tokens.skip_whitespace(true) : tokens.previous(),
isEmptyLabel = TOKEN_WHITESPACE.test(label);
// The label must be an identifier, and preceded by whitespace, or whitespace itself (the "empty label")
if (isEmptyLabel || TOKEN_IDENTIFIER.test(label) && TOKEN_WHITESPACE.test(tokens.previous()))
{
tokens.push(); // 2
var last = tokens.skip_whitespace(true),
operatorCheck = true,
isDoubleOperator = false;
// unary or binary, still disables.
// + - + x is bad because it could be (+ - + x) or (a + - + x)
// the only good is unbroken chain
if (last === '+' || last === '-'){//alert(tokens.last())
if (tokens.previous() !== last)
operatorCheck = false;
else
{
last = tokens.skip_whitespace(true);
isDoubleOperator = true;
}}
tokens.pop(); // 2
tokens.pop(); // 1
//alert(operatorCheck + "operatorCheck for " + label + " and " + last);
if (operatorCheck && (
// <)> <label><:|]>
// <}> <label><:|]>
// <]> <label><:|]>
(!isDoubleOperator && (last === TOKEN_CLOSE_BRACE)) ||
last === TOKEN_CLOSE_PARENTHESIS || last === TOKEN_CLOSE_BRACKET ||
// <.> label<:|]> --> 5. label
// <5> label<:|]>
last === TOKEN_PERIOD || TOKEN_NUMBER.test(last) ||
// <string> <label><:\]>/
last.charAt(last.length - 1) === '\"' || last.charAt(last.length - 1) === '\'' ||
// <identifier-not> <label><:|]>
TOKEN_IDENTIFIER.test(last) && !/^(new|return|case|var)$/.test(last)))
{
if (isEmptyLabel)
tuple[1] = ':';
else
{
tuple[1] = label;
if (!bracket)
tuple[1] += ':';
var count = buffer.atoms.length;
while (buffer.atoms[count--] !== label) ;
buffer.atoms.length = count;
}
return !bracket;
}
if (bracket)
return NO;
}
tokens.pop(); // 2
if (bracket)
return NO;
}
closures[2] = MAX(closures[2], 0);
}
if (instigator)
{
if (token == instigator)
@@ -775,18 +778,18 @@ objj_preprocessor.prototype.preprocess = function(tokens, /*objj_stringBuffer*/
--count;
}
// We convert import statements into objj_request_import function calls, converting
// the the file paths to use the proper search arguments.
// imports are deprecated in favor of @imort
if(token == TOKEN_IMPORT)
{
objj_fprintf(warning_stream, "import keyword is deprecated, use @import instead.");
objj_fprintf(warning_stream, this._file.path + ": import keyword is deprecated, use @import instead.");
this._import(tokens);
}
// Safari can't handle function declarations of the form function [name]([arguments]) { }
// in evals. It requires them to be in the form [name] = function([arguments]) { }. So we
// need to find these and fix them.
else if(token == TOKEN_FUNCTION)
else if (token === TOKEN_FUNCTION)
{//if (window.p) alert("function");
var accumulator = "";
@@ -796,9 +799,13 @@ objj_preprocessor.prototype.preprocess = function(tokens, /*objj_stringBuffer*/
// If the next token is an open parenthesis, we have a standard function and we don't have to
// change it:
if(token == TOKEN_OPEN_PARENTHESIS)
if (token === TOKEN_OPEN_PARENTHESIS)
{
CONCAT(buffer, "function" + accumulator + '(');
if (tuple)
++closures[1];
}
// If it's not a parenthesis, we know we have a non-supported function declaration, so fix it:
else
{
@@ -818,6 +825,9 @@ objj_preprocessor.prototype.preprocess = function(tokens, /*objj_stringBuffer*/
while((token = tokens.next()) && token != TOKEN_OPEN_BRACE)
CONCAT(buffer, token);
if (tuple)
++closures[2];
// Place the open curly brace as well, and the function name
CONCAT(buffer, token + "\n \"__FIREBUG_FNAME__" + functionName + "\".length;\n");
#endif
@@ -832,7 +842,7 @@ objj_preprocessor.prototype.preprocess = function(tokens, /*objj_stringBuffer*/
// array, or an array index.
else if (token == TOKEN_OPEN_BRACKET)
this.brackets(tokens, buffer);
// If not simply append the token.
else
CONCAT(buffer, token);