Compare commits

..

3 Commits

Author SHA1 Message Date
jeff.dyer%compilercompany.com
bbb554ffe1 ESC EA4
git-svn-id: svn://10.0.0.236/branches/MVCC-VENDOR-BRANCH@91478 18797224-902f-48f8-a5cc-f745e15eee43
2001-04-05 20:36:09 +00:00
jeff.dyer%compilercompany.com
e3aaba3727 Mountain View Compiler - Release 2
git-svn-id: svn://10.0.0.236/branches/MVCC-VENDOR-BRANCH@90430 18797224-902f-48f8-a5cc-f745e15eee43
2001-03-26 17:21:25 +00:00
(no author)
f2e55be64d This commit was manufactured by cvs2svn to create branch 'MVCC-VENDOR-
BRANCH'.

git-svn-id: svn://10.0.0.236/branches/MVCC-VENDOR-BRANCH@85592 18797224-902f-48f8-a5cc-f745e15eee43
2001-01-26 23:55:33 +00:00
400 changed files with 60223 additions and 104276 deletions

View File

@@ -0,0 +1,65 @@
# Makefile for ESC in Java
# Targets:
# all -- to build all parts.
# input, lexer, parser, semantics, generator -- to build a specfic part.
# sanity -- to run the compiler against a simple script. If things are
# working the compiler will return the value: completion( 0, okay, null )
all: util input lexer parser semantics generator runtime main sanity
main:
javac -d Debug -classpath Debug ../../src/java/main/*.java
util:
javac -d Debug -classpath Debug ../../src/java/util/*.java
input:
javac -d Debug -classpath Debug ../../src/java/input/*.java
lexer:
javac -d Debug -classpath Debug ../../src/java/lexer/*.java
parser:
javac -d Debug -classpath Debug ../../src/java/parser/*.java
semantics:
javac -d Debug -classpath Debug ../../src/java/semantics/*.java ../../src/java/semantics/values/*.java ../../src/java/semantics/types/*.java
generator:
javac -d Debug -classpath Debug ../../src/java/generator/*.java
runtime:
javac -d Debug -classpath Debug ../../src/java/runtime/*.java
testcase:
javac -d Debug -classpath Debug Script1.java
java -classpath Debug Test1 Script1
sanity:
java -classpath Debug Main ../../test/sanity.js
test:
java -classpath Debug Main -d ../../test/ecma-e4/02.expressions/primary.1.js
java -classpath Debug Main -d ../../test/ecma-e4/02.expressions/prefixunary.1.js
java -classpath Debug Main -d ../../test/ecma-e4/02.expressions/postfixunary.1.js
java -classpath Debug Main -d ../../test/ecma-e4/02.expressions/binary.1.js
java -classpath Debug Main -d ../../test/ecma-e4/03.statements/break.1.js
java -classpath Debug Main -d ../../test/ecma-e4/03.statements/continue.1.js
java -classpath Debug Main -d ../../test/ecma-e4/03.statements/do.1.js
java -classpath Debug Main -d ../../test/ecma-e4/03.statements/for.1.js
java -classpath Debug Main -d ../../test/ecma-e4/03.statements/forin.1.js
java -classpath Debug Main -d ../../test/ecma-e4/03.statements/if.1.js
java -classpath Debug Main -d ../../test/ecma-e4/03.statements/labeled.1.js
java -classpath Debug Main -d ../../test/ecma-e4/03.statements/return.1.js
java -classpath Debug Main -d ../../test/ecma-e4/03.statements/switch.1.js
java -classpath Debug Main -d ../../test/ecma-e4/03.statements/throw.1.js
java -classpath Debug Main -d ../../test/ecma-e4/03.statements/try.1.js
java -classpath Debug Main -d ../../test/ecma-e4/03.statements/while.1.js
java -classpath Debug Main -d ../../test/ecma-e4/03.statements/with.1.js
java -classpath Debug Main -d ../../test/ecma-e4/04.definitions/definition.1.js
java -classpath Debug Main -d ../../test/ecma-e4/04.definitions/definition.2.js
test_functions:
java -classpath Debug Main -debug ../../test/ecma-e4/06.functions/function.1.js

File diff suppressed because it is too large Load Diff

Binary file not shown.

View File

@@ -0,0 +1,27 @@
%PDF-1.2
%âãÏÓ
3 0 obj
<<
/Linearized 1
/O 5
/H [ 877 180 ]
/L 121458
/E 121134
/N 1
/T 121281
>>
endobj
xref
3 24
0000000016 00000 n
0000000824 00000 n
0000001057 00000 n
0000001260 00000 n
0000001362 00000 n
0000001541 00000 n
0000001563 00000 n
0000015420 00000 n
0000015443 00000 n
0000030482 00000 n
0000030505 00000 n
0000045794 00000 n

View File

@@ -0,0 +1 @@
ÐÏࡱ

View File

@@ -0,0 +1 @@
ÐÏࡱ

96
mozilla/js2/jsc/readme Normal file
View File

@@ -0,0 +1,96 @@
R E A D M E F I L E
ECMASCRIPT 3RD EDITION COMPACT PROFILE
Mountain View Compiler Company
Jeff Dyer, Jan-30-2001
OVERVIEW
ES3CP implements the ECMAScript 3rd Edition Specification,
Compact Profile subset. It translates (or will translate)
ECMAScript programs into Java class files.
STATUS
This code is an aggregation of existing ECMAScript
implementations I have written in Java. It is merely a
starting point for the development of production
ES3CP compilers in Java and C++. Some of the tasks
to be done are listed in the following section.
DEVELOPMENT SEQUENCE
This section offers a partial sequence of tasks required
to complete both the Java and C++ implementations.
A General
1 Remove 4th Edition features
2 Translate Java implementation into C++
B Code generator
1 Class file emitter
2 Load and store generation for references
3 Expressions
4 Closures
5 Statements
6 Function definitions
B Input buffer
C Lexer
D Parser
E Semantic Analyzer
1 Constant evaluation
2 Type inference
BUILDING
Before you start make sure you have a current version of the Java2 SDK
installed on your system. If it is correctly installed, you can type
'javac' at the command-line and see something like:
Usage: javac <options> <source files>
followed by a bunch of other documentation text.
NOTE: I've only tried to build on NT40 using Java2 1.3.0_01. You may
get different results in different environments.
Go to the directory ./build/java, and run your favorite make
utility, such as:
make
If all goes well, the sanity test will run and you will see something
like
../../test/sanity.js: 0 errors
on the last line of the console output. To run more extensive tests,
use the build command:
make test
There are also build targets for each of the components (input, lexer,
parser, semantics, and generator) of the compiler. Thus, a useful idiom
is to give 'make' two targets, the component you just modified followed
by the sanity test target like this:
make parser sanity
To automatically rebuild the parser and run the sanity test. What's
missing is any kind of dependency rules, so using the root target
always rebuilds everything. This, for the sake of keeping it simple.
RUNNING
From the ./build/java directory, use the following command:
java -classpath Debug Main program.js
where 'program.js' is the name of the file to compile. ES3CP will
produce a new file given the name of the original source file
with the suffix '.jsil' appended to it. Errors are written to a
file with the suffix '.err' appended to it.
CHANGES
Jan-30-2001: Initial set of files.

View File

@@ -0,0 +1,464 @@
/*
* ByteCodeFactory.cpp
*
* Emits byte code for a particular component of the classfile.
*/
#include <iostream>
#include <vector>
#include <fstream>
#include <cstdlib>
#include <algorithm>
#include "ClassFileConstants.h"
#include "ByteCodeFactory.h"
namespace esc {
namespace v1 {
std::ofstream* of;
void put_byte(unsigned byte b) {
printf("%3.2x",(unsigned char)b);
of->put((unsigned char)b);
}
/**
* Make a CONSTANT_Methodref_info
*/
std::vector<byte>& ByteCodeFactory::ConstantFieldrefInfo(
std::vector<byte>& bytes,
short class_index,
short name_and_type_index) {
bytes = Byte(bytes,CONSTANT_Fieldref);
bytes = Short(bytes,class_index);
bytes = Short(bytes,name_and_type_index);
return bytes;
}
std::vector<byte>& ByteCodeFactory::ConstantFieldrefInfo(
short class_index,
short name_and_type_index) {
return ConstantFieldrefInfo(*new std::vector<byte>(),class_index,name_and_type_index);
}
/**
* Make a CONSTANT_Methodref_info
*/
std::vector<byte>& ByteCodeFactory::ConstantMethodrefInfo(
std::vector<byte>& bytes,
short class_index,
short name_and_type_index) {
bytes = Byte(bytes,CONSTANT_Methodref);
bytes = Short(bytes,class_index);
bytes = Short(bytes,name_and_type_index);
return bytes;
}
std::vector<byte>& ByteCodeFactory::ConstantMethodrefInfo(
short class_index,
short name_and_type_index) {
return ConstantMethodrefInfo(*new std::vector<byte>(),class_index,name_and_type_index);
}
/**
* Make a Constant Pool
*/
std::vector<byte>& ByteCodeFactory::ConstantPool(
std::vector<byte>& bytes,
std::vector<std::vector<byte>*>& constants) {
for(int i=0;i<constants.size();i++) {
bytes.insert(bytes.end(),constants[i]->begin(),constants[i]->end());
}
return bytes;
}
/**
* Make an Interfaces table
*/
std::vector<byte>& ByteCodeFactory::Interfaces(
std::vector<byte>& bytes,
std::vector<std::vector<byte>*>& interfaces) {
for(int i=0;i<interfaces.size();i++) {
bytes.insert(bytes.end(),interfaces[i]->begin(),interfaces[i]->end());
}
return bytes;
}
/**
* Make a Fields table
*/
std::vector<byte>& ByteCodeFactory::Fields(
std::vector<byte>& bytes,
std::vector<std::vector<byte>*>& fields) {
for(int i=0;i<fields.size();i++) {
bytes.insert(bytes.end(),fields[i]->begin(),fields[i]->end());
}
return bytes;
}
/**
* Make a Methods table
*/
std::vector<byte>& ByteCodeFactory::Methods(
std::vector<byte>& bytes,
std::vector<std::vector<byte>*>& methods) {
for(int i=0;i<methods.size();i++) {
bytes.insert(bytes.end(),methods[i]->begin(),methods[i]->end());
}
return bytes;
}
/**
* Make an Attributes table
*/
std::vector<byte>& ByteCodeFactory::Attributes(
std::vector<byte>& bytes,
std::vector<std::vector<byte>*>& attributes) {
for(int i=0;i<attributes.size();i++) {
bytes.insert(bytes.end(),attributes[i]->begin(),attributes[i]->end());
}
return bytes;
}
/**
* Make a CONSTANT_Utf8_info
*/
std::vector<byte>& ByteCodeFactory::ConstantUtf8Info(
std::vector<byte>& bytes,
const char* text) {
int text_length = strlen(text);
bytes = Byte(bytes,CONSTANT_Utf8);
bytes = Short(bytes,text_length);
bytes.insert(bytes.end(),text,text+text_length);
return bytes;
}
std::vector<byte>& ByteCodeFactory::ConstantUtf8Info(
const char* text) {
return ConstantUtf8Info(*new std::vector<byte>(),text);
}
/**
* Make a CONSTANT_String_info
*/
std::vector<byte>& ByteCodeFactory::ConstantStringInfo(
std::vector<byte>& bytes,
short index) {
bytes = Byte(bytes,CONSTANT_String);
bytes = Short(bytes,index);
return bytes;
}
std::vector<byte>& ByteCodeFactory::ConstantStringInfo(
short index) {
return ConstantStringInfo(*new std::vector<byte>(),index);
}
/**
* Make a CONSTANT_Class_info
*/
std::vector<byte>& ByteCodeFactory::ConstantClassInfo(
std::vector<byte>& bytes,
short name_index) {
bytes = Byte(bytes,CONSTANT_Class);
bytes = Short(bytes,name_index);
return bytes;
}
std::vector<byte>& ByteCodeFactory::ConstantClassInfo(
short name_index) {
return ConstantClassInfo(*new std::vector<byte>(),name_index);
}
/**
* Make a CONSTANT_NameAndType_info
*/
std::vector<byte>& ByteCodeFactory::ConstantNameAndTypeInfo(
std::vector<byte>& bytes,
short name_index,
short descriptor_index) {
bytes = Byte(bytes,CONSTANT_NameAndType);
bytes = Short(bytes,name_index);
bytes = Short(bytes,descriptor_index);
return bytes;
}
std::vector<byte>& ByteCodeFactory::ConstantNameAndTypeInfo(
short name_index,
short descriptor_index) {
return ConstantNameAndTypeInfo(*new std::vector<byte>(),name_index,descriptor_index);
}
/**
* Make a method_info
*/
std::vector<byte>& ByteCodeFactory::MethodInfo(
std::vector<byte>& bytes,
short access_flags,
short name_index,
short descriptor_index,
short attributes_count,
std::vector<byte>& attributes) {
bytes = Short(bytes,access_flags);
bytes = Short(bytes,name_index);
bytes = Short(bytes,descriptor_index);
bytes = Short(bytes,attributes_count);
if( attributes_count != 0 ) {
bytes.insert(bytes.end(),attributes.begin(),attributes.end());
}
return bytes;
}
/**
* Make a Code_attribute
*/
std::vector<byte>& ByteCodeFactory::CodeAttribute(
std::vector<byte>& bytes,
short attribute_name_index,
int attribute_length,
short max_stack,
short max_locals,
int code_length,
std::vector<byte>& code,
short exception_table_length,
std::vector<byte>& exception_table,
short attributes_count,
std::vector<byte>& attributes) {
Short(bytes,attribute_name_index);
Int(bytes,attribute_length);
Short(bytes,max_stack);
Short(bytes,max_locals);
Int(bytes,code_length);
if( code_length != 0 ) {
bytes.insert(bytes.end(),code.begin(),code.end());
}
Short(bytes,exception_table_length);
if( exception_table_length != 0 ) {
bytes.insert(bytes.end(),exception_table.begin(),exception_table.end());
}
Short(bytes,attributes_count);
if( code_length != 0 ) {
bytes.insert(bytes.end(),attributes.begin(),attributes.end());
}
return bytes;
}
/**
* Make a class file.
*/
std::vector<byte>& ByteCodeFactory::ClassFile(std::vector<byte>& bytes, char* classname) {
int magic = 0xCAFEBABE;
short minor_version = 0;
short major_version = 46;
// Constants - a vector of byte vectors.
//
std::vector<std::vector<byte>*>& constants = *new std::vector<std::vector<byte>*>();
constants.push_back(new std::vector<byte>());
ConstantMethodrefInfo(*constants.back(),(short)3,(short)7);
constants.push_back(new std::vector<byte>());
ConstantClassInfo(*constants.back(),(short)8);
constants.push_back(new std::vector<byte>());
ConstantClassInfo(*constants.back(),(short)9);
constants.push_back(new std::vector<byte>());
ConstantUtf8Info(*constants.back(),"<init>");
constants.push_back(new std::vector<byte>());
ConstantUtf8Info(*constants.back(),"()V");
constants.push_back(new std::vector<byte>());
ConstantUtf8Info(*constants.back(),"Code");
constants.push_back(new std::vector<byte>());
ConstantNameAndTypeInfo(*constants.back(),(short)4,(short)5);
constants.push_back(new std::vector<byte>());
ConstantUtf8Info(*constants.back(),classname);
constants.push_back(new std::vector<byte>());
ConstantUtf8Info(*constants.back(),"java/lang/Object");
constants.push_back(new std::vector<byte>());
ConstantUtf8Info(*constants.back(),"main");
constants.push_back(new std::vector<byte>());
ConstantUtf8Info(*constants.back(),"([Ljava/lang/String;)V");
constants.push_back(new std::vector<byte>());
ConstantNameAndTypeInfo(*constants.back(),(short)10,(short)11);
short constant_pool_count = (short)(constants.size()+1);
// Class structure
short access_flags = ACC_SUPER|ACC_PUBLIC;
short this_class = 2;
short super_class = 3;
short interfaces_count = 0;
std::vector<std::vector<byte>*>& interfaces = *new std::vector<std::vector<byte>*>();
short fields_count = 0;
std::vector<std::vector<byte>*>& fields = *new std::vector<std::vector<byte>*>();
// Methods
std::vector<byte>& exception_table_bytes = *new std::vector<byte>();
std::vector<byte>& code_attributes_bytes = *new std::vector<byte>();
std::vector<std::vector<byte>*>& methods = *new std::vector<std::vector<byte>*>();
std::vector<byte>& code_bytes2 = *new std::vector<byte>();
Byte(code_bytes2,(byte)0x2a); //
Byte(code_bytes2,(byte)0xb7);
Byte(code_bytes2,(byte)0x00);
Byte(code_bytes2,(byte)0x01);
Byte(code_bytes2,(byte)0xb1);
std::vector<byte>& code_attribute2 = *new std::vector<byte>();
code_attribute2 = CodeAttribute(code_attribute2,(short)6,17,(short)1,(short)1,5,code_bytes2,(short)0,exception_table_bytes,(short)0,code_attributes_bytes);
methods.push_back(new std::vector<byte>());
MethodInfo(*methods.back(),(short)0,(short)4,(short)5,(short)1,code_attribute2);
delete &code_attribute2;
delete &code_bytes2;
std::vector<byte>& code_bytes1 = *new std::vector<byte>();
Byte(code_bytes1,(byte)0xb1); //
std::vector<byte>& code_attribute1 = *new std::vector<byte>();
code_attribute1 = CodeAttribute(code_attribute1,(short)6,13,(short)0,(short)1,1,code_bytes1,(short)0,exception_table_bytes,(short)0,code_attributes_bytes);
methods.push_back(new std::vector<byte>());
MethodInfo(*methods.back(),(short)(ACC_PUBLIC|ACC_STATIC),(short)10,(short)11,(short)1,code_attribute1);
short methods_count = (short)methods.size();
delete &code_attribute1;
delete &code_bytes1;
// Attributes
short attributes_count = 0;
std::vector<std::vector<byte>*>& attributes = *new std::vector<std::vector<byte>*>();
ClassFile(bytes,magic,minor_version,major_version,constant_pool_count,
constants,access_flags,this_class,super_class,interfaces_count,
interfaces,fields_count,fields,methods_count,methods,
attributes_count,attributes);
return bytes;
}
std::vector<byte>& ByteCodeFactory::ClassFile(
std::vector<byte>& bytes,
int magic,
short minor_version,
short major_version,
short constant_pool_count,
std::vector<std::vector<byte>*>& constant_pool,
short access_flags,
short this_class,
short super_class,
short interfaces_count,
std::vector<std::vector<byte>*>& interfaces,
short fields_count,
std::vector<std::vector<byte>*>& fields,
short methods_count,
std::vector<std::vector<byte>*>& methods,
short attributes_count,
std::vector<std::vector<byte>*>& attributes ) {
Int(bytes,magic);
Short(bytes,minor_version);
Short(bytes,major_version);
Short(bytes,constant_pool_count);
if( constant_pool_count != 0 ) {
bytes = ConstantPool(bytes,constant_pool);
}
Short(bytes,access_flags);
Short(bytes,this_class);
Short(bytes,super_class);
Short(bytes,interfaces_count);
if( interfaces_count != 0 ) {
bytes = Interfaces(bytes,interfaces);
}
Short(bytes,fields_count);
if( fields_count != 0 ) {
bytes = Fields(bytes,fields);
}
Short(bytes,methods_count);
if( methods_count != 0 ) {
bytes = Methods(bytes,methods);
}
Short(bytes,attributes_count);
if( attributes_count != 0 ) {
bytes = Attributes(bytes,attributes);
}
return bytes;
}
/*
* Test driver
*/
int ByteCodeFactory::main(int argc, char* argv[]) {
of = new std::ofstream("TestByteCodeGenerator.class",std::ios::binary);
std::vector<byte> &bytes=*new std::vector<byte>();
ClassFile(bytes,"TestByteCodeGenerator");
printf("\n\nTestByteCodeGenerator.class: ");
std::for_each(bytes.begin(),bytes.end(),put_byte);
delete &bytes;
return 0;
};
};
};
/*
* Written by Jeff Dyer
* Copyright (c) 1998-2001 by Mountain View Compiler Company
* All rights reserved.
*/

View File

@@ -0,0 +1,205 @@
/*
* ByteCodeFactory.h
*
* Emits byte code for a particular component of the classfile.
*/
#ifndef ByteCodeFactory_h
#define ByteCodeFactory_h
#include <string>
#include <vector>
#include <fstream>
#include <cstdlib>
#include "ClassFileConstants.h"
#define byte char
namespace esc {
namespace v1 {
class ByteCodeFactory: protected ClassFileConstants {
public:
private:
enum { debug = false, };
std::string name;
std::vector<char> bytes;
public:
/*
* Tags
*/
enum {
CONSTANT_Utf8 = 0x01,
CONSTANT_Class = 0x07,
CONSTANT_String = 0x08,
CONSTANT_Methodref = 0x0a,
CONSTANT_NameAndType = 0x0c,
};
/*
* Class access and property modifiers
*/
enum {
ACC_PUBLIC = 0x0001,
ACC_STATIC = 0x0008,
ACC_FINAL = 0x0010,
ACC_SUPER = 0x0020,
ACC_INTERFACE = 0x0200,
ACC_ABSTRACT = 0x0400,
};
static std::vector<byte>& ConstantFieldrefInfo(
std::vector<byte>& bytes,
short class_index,
short name_and_type_index);
static std::vector<byte>& ConstantFieldrefInfo(
short class_index,
short name_and_type_index);
static std::vector<byte>& ConstantMethodrefInfo(
std::vector<byte>& bytes,
short class_index,
short name_and_type_index);
static std::vector<byte>& ConstantMethodrefInfo(
short class_index,
short name_and_type_index);
static std::vector<byte>& ConstantPool(
std::vector<byte>& bytes,
std::vector<std::vector<byte>*>& constants);
static std::vector<byte>& Interfaces(
std::vector<byte>& bytes,
std::vector<std::vector<byte>*>& interfaces);
static std::vector<byte>& Fields(
std::vector<byte>& bytes,
std::vector<std::vector<byte>*>& fields);
static std::vector<byte>& Methods(
std::vector<byte>& bytes,
std::vector<std::vector<byte>*>& methods);
static std::vector<byte>& Attributes(
std::vector<byte>& bytes,
std::vector<std::vector<byte>*>& attributes);
static std::vector<byte>& ConstantUtf8Info(
std::vector<byte>& bytes,
const char* text);
static std::vector<byte>& ConstantUtf8Info(
const char* text);
static std::vector<byte>& ConstantStringInfo(
std::vector<byte>& bytes,
short index);
static std::vector<byte>& ConstantStringInfo(
short index);
static std::vector<byte>& ConstantClassInfo(
std::vector<byte>& bytes,
short name_index);
static std::vector<byte>& ConstantClassInfo(
short name_index);
static std::vector<byte>& ConstantNameAndTypeInfo(
std::vector<byte>& bytes,
short name_index,
short descriptor_index);
static std::vector<byte>& ConstantNameAndTypeInfo(
short name_index,
short descriptor_index);
static std::vector<byte>& MethodInfo(
std::vector<byte>& bytes,
short access_flags,
short name_index,
short descriptor_index,
short attributes_count,
std::vector<byte>& attributes);
static std::vector<byte>& CodeAttribute(
std::vector<byte>& bytes,
short attribute_name_index,
int attribute_length,
short max_stack,
short max_locals,
int code_length,
std::vector<byte>& code,
short exception_table_length,
std::vector<byte>& exception_table,
short attributes_count,
std::vector<byte>& attributes);
/**
* Make a class file.
*/
static std::vector<byte>& ClassFile(
std::vector<byte>& bytes,
int magic,
short minor_version,
short major_version,
short constant_pool_count,
std::vector<std::vector<byte>*>& constant_pool,
short access_flags,
short this_class,
short super_class,
short interfaces_count,
std::vector<std::vector<byte>*>& interfaces,
short fields_count,
std::vector<std::vector<byte>*>& fields,
short methods_count,
std::vector<std::vector<byte>*>& methods,
short attributes_count,
std::vector<std::vector<byte>*>& attributes );
static std::vector<byte>& ClassFile(std::vector<byte>& bytes, char* classname);
static std::vector<byte>& Byte(std::vector<byte>& bytes, byte v) {
bytes.push_back((byte)v);
return bytes;
}
static std::vector<byte>& Short(std::vector<byte>& bytes, unsigned short v) {
bytes.push_back((byte)(v>>8));
bytes.push_back((byte)v);
return bytes;
}
static std::vector<byte>& Int(std::vector<byte>& bytes, unsigned int v) {
bytes.push_back((byte)(v>>24));
bytes.push_back((byte)(v>>16));
bytes.push_back((byte)(v>>8));
bytes.push_back((byte)v);
return bytes;
}
static int main(int argc, char* argv[]);
};
}
}
#endif // ByteCodeFactory_h
/*
* Copyright (c) 1998-2001 by Mountain View Compiler Company
* All rights reserved.
*/

View File

@@ -0,0 +1,261 @@
#ifndef ClassFileConstants_h
#define ClassFileConstants_h
/*
* ClassFileConstants
*/
namespace esc {
namespace v1 {
struct ClassFileConstants {
enum {
debug = false
};
/*
* Tags
*/
enum {
CONSTANT_Utf8 = 0x01,
CONSTANT_Class = 0x07,
CONSTANT_Fieldref = 0x09,
CONSTANT_Methodref = 0x0a,
CONSTANT_NameAndType = 0x0c,
};
/*
* Class access and property modifiers
*/
enum {
ACC_PUBLIC = 0x0001,
ACC_STATIC = 0x0008,
ACC_FINAL = 0x0010,
ACC_SUPER = 0x0020,
ACC_INTERFACE = 0x0200,
ACC_ABSTRACT = 0x0400,
};
/*
* Opcodes
*/
enum {
OP_nop = (char) 0x00,
OP_aconst_null = (char) 0x01,
OP_iconst_m1 = (char) 0x02,
OP_iconst_0 = (char) 0x03,
OP_iconst_1 = (char) 0x04,
OP_iconst_2 = (char) 0x05,
OP_iconst_3 = (char) 0x06,
OP_iconst_4 = (char) 0x07,
OP_iconst_5 = (char) 0x08,
OP_lconst_0 = (char) 0x09,
OP_lconst_1 = (char) 0x0a,
OP_fconst_0 = (char) 0x0b,
OP_fconst_1 = (char) 0x0c,
OP_fconst_2 = (char) 0x0d,
OP_dconst_0 = (char) 0x0e,
OP_dconst_1 = (char) 0x0f,
OP_bipush = (char) 0x10,
OP_sipush = (char) 0x11,
OP_ldc = (char) 0x12,
OP_ldc_w = (char) 0x13,
OP_ldc2_w = (char) 0x14,
OP_iload = (char) 0x15,
OP_lload = (char) 0x16,
OP_fload = (char) 0x17,
OP_dload = (char) 0x18,
OP_aload = (char) 0x19,
OP_iload_0 = (char) 0x1a,
OP_iload_1 = (char) 0x1b,
OP_iload_2 = (char) 0x1c,
OP_iload_3 = (char) 0x1d,
OP_lload_0 = (char) 0x1e,
OP_lload_1 = (char) 0x1f,
OP_lload_2 = (char) 0x20,
OP_lload_3 = (char) 0x21,
OP_fload_0 = (char) 0x22,
OP_fload_1 = (char) 0x23,
OP_fload_2 = (char) 0x24,
OP_fload_3 = (char) 0x25,
OP_dload_0 = (char) 0x26,
OP_dload_1 = (char) 0x27,
OP_dload_2 = (char) 0x28,
OP_dload_3 = (char) 0x29,
OP_aload_0 = (char) 0x2a,
OP_aload_1 = (char) 0x2b,
OP_aload_2 = (char) 0x2c,
OP_aload_3 = (char) 0x2d,
OP_iaload = (char) 0x2e,
OP_laload = (char) 0x2f,
OP_faload = (char) 0x30,
OP_daload = (char) 0x31,
OP_aaload = (char) 0x32,
OP_baload = (char) 0x33,
OP_caload = (char) 0x34,
OP_saload = (char) 0x35,
OP_istore = (char) 0x36,
OP_lstore = (char) 0x37,
OP_fstore = (char) 0x38,
OP_dstore = (char) 0x39,
OP_astore = (char) 0x3a,
OP_istore_0 = (char) 0x3b,
OP_istore_1 = (char) 0x3c,
OP_istore_2 = (char) 0x3d,
OP_istore_3 = (char) 0x3e,
OP_lstore_0 = (char) 0x3f,
OP_lstore_1 = (char) 0x40,
OP_lstore_2 = (char) 0x41,
OP_lstore_3 = (char) 0x42,
OP_fstore_0 = (char) 0x43,
OP_fstore_1 = (char) 0x44,
OP_fstore_2 = (char) 0x45,
OP_fstore_3 = (char) 0x46,
OP_dstore_0 = (char) 0x47,
OP_dstore_1 = (char) 0x48,
OP_dstore_2 = (char) 0x49,
OP_dstore_3 = (char) 0x4a,
OP_astore_0 = (char) 0x4b,
OP_astore_1 = (char) 0x4c,
OP_astore_2 = (char) 0x4d,
OP_astore_3 = (char) 0x4e,
OP_iastore = (char) 0x4f,
OP_lastore = (char) 0x50,
OP_fastore = (char) 0x51,
OP_dastore = (char) 0x52,
OP_aastore = (char) 0x53,
OP_bastore = (char) 0x54,
OP_castore = (char) 0x55,
OP_sastore = (char) 0x56,
OP_pop = (char) 0x57,
OP_pop2 = (char) 0x58,
OP_dup = (char) 0x59,
OP_dup_x1 = (char) 0x5a,
OP_dup_x2 = (char) 0x5b,
OP_dup2 = (char) 0x5c,
OP_dup2_x1 = (char) 0x5d,
OP_dup2_x2 = (char) 0x5e,
OP_swap = (char) 0x5f,
OP_iadd = (char) 0x60,
OP_ladd = (char) 0x61,
OP_fadd = (char) 0x62,
OP_dadd = (char) 0x63,
OP_isub = (char) 0x64,
OP_lsub = (char) 0x65,
OP_fsub = (char) 0x66,
OP_dsub = (char) 0x67,
OP_imul = (char) 0x68,
OP_lmul = (char) 0x69,
OP_fmul = (char) 0x6a,
OP_dmul = (char) 0x6b,
OP_idiv = (char) 0x6c,
OP_ldiv = (char) 0x6d,
OP_fdiv = (char) 0x6e,
OP_ddiv = (char) 0x6f,
OP_irem = (char) 0x70,
OP_lrem = (char) 0x71,
OP_frem = (char) 0x72,
OP_drem = (char) 0x73,
OP_ineg = (char) 0x74,
OP_lneg = (char) 0x75,
OP_fneg = (char) 0x76,
OP_dneg = (char) 0x77,
OP_ishl = (char) 0x78,
OP_lshl = (char) 0x79,
OP_ishr = (char) 0x7a,
OP_lshr = (char) 0x7b,
OP_iushr = (char) 0x7c,
OP_lushr = (char) 0x7d,
OP_iand = (char) 0x7e,
OP_land = (char) 0x7f,
OP_ior = (char) 0x80,
OP_lor = (char) 0x81,
OP_ixor = (char) 0x82,
OP_lxor = (char) 0x83,
OP_iinc = (char) 0x84,
OP_i2l = (char) 0x85,
OP_i2f = (char) 0x86,
OP_i2d = (char) 0x87,
OP_l2i = (char) 0x88,
OP_l2f = (char) 0x89,
OP_l2d = (char) 0x8a,
OP_f2i = (char) 0x8b,
OP_f2l = (char) 0x8c,
OP_f2d = (char) 0x8d,
OP_d2i = (char) 0x8e,
OP_d2l = (char) 0x8f,
OP_d2f = (char) 0x90,
OP_i2b = (char) 0x91,
OP_i2c = (char) 0x92,
OP_i2s = (char) 0x93,
OP_lcmp = (char) 0x94,
OP_fcmpl = (char) 0x95,
OP_fcmpg = (char) 0x96,
OP_dcmpl = (char) 0x97,
OP_dcmpg = (char) 0x98,
OP_ifeq = (char) 0x99,
OP_ifne = (char) 0x9a,
OP_iflt = (char) 0x9b,
OP_ifge = (char) 0x9c,
OP_ifgt = (char) 0x9d,
OP_ifle = (char) 0x9e,
OP_if_icmpeq = (char) 0x9f,
OP_if_icmpne = (char) 0xa0,
OP_if_icmplt = (char) 0xa1,
OP_if_icmpge = (char) 0xa3,
OP_if_icmple = (char) 0xa4,
OP_if_acmpeq = (char) 0xa5,
OP_if_acmpne = (char) 0xa6,
OP_goto = (char) 0xa7,
OP_jsr = (char) 0xa8,
OP_ret = (char) 0xa9,
OP_tableswitch = (char) 0xaa,
OP_lookupswitch = (char) 0xab,
OP_ireturn = (char) 0xac,
OP_lreturn = (char) 0xad,
OP_freturn = (char) 0xae,
OP_dreturn = (char) 0xaf,
OP_areturn = (char) 0xb0,
OP_return = (char) 0xb1,
OP_getstatic = (char) 0xb2,
OP_putstatic = (char) 0xb3,
OP_getfield = (char) 0xb4,
OP_putfield = (char) 0xb5,
OP_invokevirtual = (char) 0xb6,
OP_invokespecial = (char) 0xb7,
OP_invokestatic = (char) 0xb8,
OP_invokeinterface = (char) 0xb9,
OP_xxxunusedxxx = (char) 0xba,
OP_new = (char) 0xbb,
OP_newarray = (char) 0xbc,
OP_anewarray = (char) 0xbd,
OP_arraylength = (char) 0xbe,
OP_athrow = (char) 0xbf,
OP_checkcast = (char) 0xc0,
OP_instanceof = (char) 0xc1,
OP_monitorenter = (char) 0xc2,
OP_monitorexit = (char) 0xc3,
OP_wide = (char) 0xc4,
OP_multianewarray = (char) 0xc5,
OP_ifnull = (char) 0xc6,
OP_ifnonnull = (char) 0xc7,
OP_goto_w = (char) 0xc8,
OP_jsr_w = (char) 0xc9,
OP_breakpoint = (char) 0xca,
OP_impdep1 = (char) 0xfe,
OP_impdep2 = (char) 0xff,
};
};
}
}
#endif // ClassFileConstants_h
/*
* Copyright (c) 1998-2001 by Mountain View Compiler Company
* All rights reserved.
*/

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,201 @@
/*
* ClassFileGenerator
*/
#ifndef ClassFileGenerator_h
#define ClassFileGenerator_h
#include <vector>
#include "Value.h"
#include "Context.h"
#include "Evaluator.h"
#include "ByteCodeFactory.h"
//#include "ClassFileConstants.h"
namespace esc {
namespace v1 {
class ClassFileGenerator : public Evaluator, private ByteCodeFactory {
struct ClassFile : protected ClassFileConstants {
int magic;
short minor_version;
short major_version;
std::vector<std::vector<byte>*>* constant_pool;
short constant_pool_count;
short access_flags;
short this_class;
short super_class;
short interfaces_count;
std::vector<std::vector<byte>*>* interfaces;
short fields_count;
std::vector<std::vector<byte>*>* fields;
// start method
std::vector<byte>* exception_table;
std::vector<byte>* code_attributes;
std::vector<std::vector<byte>*>* methods;
std::vector<byte>* code; // use this for the start method (the global script)
short methods_count;
short attributes_count;
std::vector<std::vector<byte>*>* attributes;
ClassFile() :
magic(0xCAFEBABE),
minor_version(0),
major_version(46),
constant_pool(new std::vector<std::vector<byte>*>()),
constant_pool_count((short)0),
access_flags(ACC_SUPER|ACC_PUBLIC),
this_class((short)2),
super_class((short)3),
interfaces_count((short)0),
interfaces(new std::vector<std::vector<byte>*>()),
fields_count(0),
fields(new std::vector<std::vector<byte>*>()),
exception_table(new std::vector<byte>()),
code_attributes(new std::vector<byte>()),
methods(new std::vector<std::vector<byte>*>()),
code(new std::vector<byte>()),
methods_count(0),
attributes_count(0),
attributes(new std::vector<std::vector<byte>*>())
{
}
~ClassFile() {
delete constant_pool;
delete interfaces;
delete fields;
delete exception_table;
delete code_attributes;
delete methods;
delete code;
delete attributes;
}
short addConstant(std::vector<byte>& bytes);
};
ClassFile& cf;
char max_locals; // use to allocate local variables
void init(std::string scriptname);
public:
/*
* Test driver
*/
static int main(int argc, char* argv[]);
/*
*/
ClassFileGenerator(std::string scriptname)
: cf(*new ClassFile()) {
init(scriptname);
};
~ClassFileGenerator() {
delete &cf;
}
std::vector<byte>& emit(std::vector<byte>& bytes);
// Base node
Value* evaluate( Context& cx, Node* node );
// 3rd Edition features
Value* evaluate( Context& cx, IdentifierNode* node );
Value* evaluate( Context& cx, ThisExpressionNode* node );
Value* evaluate( Context& cx, LiteralBooleanNode* node );
Value* evaluate( Context& cx, LiteralNumberNode* node );
Value* evaluate( Context& cx, LiteralStringNode* node );
Value* evaluate( Context& cx, LiteralUndefinedNode* node );
Value* evaluate( Context& cx, LiteralRegExpNode* node );
Value* evaluate( Context& cx, FunctionExpressionNode* node );
Value* evaluate( Context& cx, ParenthesizedExpressionNode* node );
Value* evaluate( Context& cx, ParenthesizedListExpressionNode* node );
Value* evaluate( Context& cx, LiteralObjectNode* node );
Value* evaluate( Context& cx, LiteralFieldNode* node );
Value* evaluate( Context& cx, LiteralArrayNode* node );
Value* evaluate( Context& cx, PostfixExpressionNode* node );
Value* evaluate( Context& cx, NewExpressionNode* node );
Value* evaluate( Context& cx, IndexedMemberExpressionNode* node );
Value* evaluate( Context& cx, MemberExpressionNode* node );
Value* evaluate( Context& cx, CallExpressionNode* node );
Value* evaluate( Context& cx, GetExpressionNode* node );
Value* evaluate( Context& cx, SetExpressionNode* node );
Value* evaluate( Context& cx, UnaryExpressionNode* node );
Value* evaluate( Context& cx, BinaryExpressionNode* node );
Value* evaluate( Context& cx, ConditionalExpressionNode* node );
Value* evaluate( Context& cx, AssignmentExpressionNode* node );
Value* evaluate( Context& cx, ListNode* node );
Value* evaluate( Context& cx, StatementListNode* node );
Value* evaluate( Context& cx, EmptyStatementNode* node );
Value* evaluate( Context& cx, ExpressionStatementNode* node );
Value* evaluate( Context& cx, AnnotatedBlockNode* node );
Value* evaluate( Context& cx, LabeledStatementNode* node );
Value* evaluate( Context& cx, IfStatementNode* node );
Value* evaluate( Context& cx, SwitchStatementNode* node );
Value* evaluate( Context& cx, CaseLabelNode* node );
Value* evaluate( Context& cx, DoStatementNode* node );
Value* evaluate( Context& cx, WhileStatementNode* node );
Value* evaluate( Context& cx, ForInStatementNode* node );
Value* evaluate( Context& cx, ForStatementNode* node );
Value* evaluate( Context& cx, WithStatementNode* node );
Value* evaluate( Context& cx, ContinueStatementNode* node );
Value* evaluate( Context& cx, BreakStatementNode* node );
Value* evaluate( Context& cx, ReturnStatementNode* node );
Value* evaluate( Context& cx, ThrowStatementNode* node );
Value* evaluate( Context& cx, TryStatementNode* node );
Value* evaluate( Context& cx, CatchClauseNode* node );
Value* evaluate( Context& cx, FinallyClauseNode* node );
Value* evaluate( Context& cx, AnnotatedDefinitionNode* node );
Value* evaluate( Context& cx, VariableDefinitionNode* node );
Value* evaluate( Context& cx, VariableBindingNode* node );
Value* evaluate( Context& cx, FunctionDefinitionNode* node );
Value* evaluate( Context& cx, FunctionDeclarationNode* node );
Value* evaluate( Context& cx, FunctionNameNode* node );
Value* evaluate( Context& cx, FunctionSignatureNode* node );
Value* evaluate( Context& cx, ParameterNode* node );
Value* evaluate( Context& cx, ProgramNode* node );
// 4th Edition features
Value* evaluate( Context& cx, QualifiedIdentifierNode* node );
Value* evaluate( Context& cx, UnitExpressionNode* node );
Value* evaluate( Context& cx, ClassofExpressionNode* node );
Value* evaluate( Context& cx, CoersionExpressionNode* node );
Value* evaluate( Context& cx, UseStatementNode* node );
Value* evaluate( Context& cx, IncludeStatementNode* node );
Value* evaluate( Context& cx, ImportDefinitionNode* node );
Value* evaluate( Context& cx, ImportBindingNode* node );
Value* evaluate( Context& cx, AttributeListNode* node );
Value* evaluate( Context& cx, ExportDefinitionNode* node );
Value* evaluate( Context& cx, ExportBindingNode* node );
Value* evaluate( Context& cx, TypedVariableNode* node );
Value* evaluate( Context& cx, OptionalParameterNode* node );
Value* evaluate( Context& cx, ClassDefinitionNode* node );
Value* evaluate( Context& cx, ClassDeclarationNode* node );
Value* evaluate( Context& cx, InheritanceNode* node );
Value* evaluate( Context& cx, NamespaceDefinitionNode* node );
Value* evaluate( Context& cx, PackageDefinitionNode* node );
};
}
}
#endif // ClassFileGenerator_h
/*
* Copyright (c) 1998-2001 by Mountain View Compiler Company
* All rights reserved.
*/

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,498 @@
/*
* InputBuffer - filters and buffers characters from a Reader.
*/
#pragma warning( disable : 4786 )
static bool debug = false;
static bool debug_nextchar = false;
static bool debug_retract = false;
#include <string>
#include "inputbuffer.h"
namespace esc {
namespace v1 {
#if 0
StringBuffer lineA = new StringBuffer();
StringBuffer lineB = new StringBuffer();
StringBuffer curr_line,prev_line;
int curr_line_offset,prev_line_offset;
int lineA_offset, lineB_offset;
private StringBuffer text;
private int[] line_breaks = new int[1000];
Reader in;
PrintStream err;
String origin;
int pos;
int colPos, lnNum=-1; // <0,0> is the position of the first character.
public static PrintStream out;
public static void setOut(String filename) throws Exception {
out = new PrintStream( new FileOutputStream(filename) );
}
public static void main(String[] args) {
test_retract();
test_markandcopy();
test_getLineText();
}
public InputBuffer( Reader in, PrintStream err, String origin ) {
this(in,err,origin,0);
}
public InputBuffer( Reader in, PrintStream err, String origin, int pos ) {
this.in = in;
this.err = err;
this.origin = origin;
this.pos = pos;
this.text = new StringBuffer();
}
/**
* read()
*
* Read the next character from the input reader and store it in a buffer
* of the full text.
*/
private int read() throws Exception {
int c = in.read();
text.append((char)c);
pos++;
return c;
}
/**
* text()
*/
public String source() {
return text.toString();
}
/**
* nextchar() --
*
* The basic function of nextchar() is to fetch the next character,
* in the input array, increment next and return the fetched character.
*
* To simplify the Scanner, this method also does the following:
* 1. normalizes certain special characters to a common character.
* 2. skips unicode format control characters (category Cf).
* 3. keeps track of line breaks, line position and line number.
* 4. treats <cr>+<lf> as a single line terminator.
* 5. returns 0 when the end of input is reached.
*/
public final int nextchar() throws Exception {
int c = -1;
// If the last character was at the end of a line,
// then swap buffers and fill the new one with characters
// from the input reader.
if( curr_line==null || colPos==curr_line.length() ) {
lnNum++;
colPos=0;
// If the current character is a newline, then read
// the next line of input into the other input buffer.
if( curr_line == lineA ) {
if( lineB == null ) {
lineB = new StringBuffer();
lineB_offset = pos;
}
curr_line = lineB; curr_line_offset = lineB_offset;
prev_line = lineA; prev_line_offset = lineA_offset;
lineA = null;
} else {
if( lineA == null ) {
lineA = new StringBuffer();
lineA_offset = pos;
}
curr_line = lineA; curr_line_offset = lineA_offset;
prev_line = lineB; prev_line_offset = lineB_offset;
lineB = null;
}
while(c != '\n' && c != 0) {
c = read();
if( false ) {
Debugger.trace( "c = " + c );
}
// Skip Unicode 3.0 format-control (general category Cf in
// Unicode Character Database) characters.
while(true) {
switch(c) {
case 0x070f: // SYRIAC ABBREVIATION MARK
case 0x180b: // MONGOLIAN FREE VARIATION SELECTOR ONE
case 0x180c: // MONGOLIAN FREE VARIATION SELECTOR TWO
case 0x180d: // MONGOLIAN FREE VARIATION SELECTOR THREE
case 0x180e: // MONGOLIAN VOWEL SEPARATOR
case 0x200c: // ZERO WIDTH NON-JOINER
case 0x200d: // ZERO WIDTH JOINER
case 0x200e: // LEFT-TO-RIGHT MARK
case 0x200f: // RIGHT-TO-LEFT MARK
case 0x202a: // LEFT-TO-RIGHT EMBEDDING
case 0x202b: // RIGHT-TO-LEFT EMBEDDING
case 0x202c: // POP DIRECTIONAL FORMATTING
case 0x202d: // LEFT-TO-RIGHT OVERRIDE
case 0x202e: // RIGHT-TO-LEFT OVERRIDE
case 0x206a: // INHIBIT SYMMETRIC SWAPPING
case 0x206b: // ACTIVATE SYMMETRIC SWAPPING
case 0x206c: // INHIBIT ARABIC FORM SHAPING
case 0x206d: // ACTIVATE ARABIC FORM SHAPING
case 0x206e: // NATIONAL DIGIT SHAPES
case 0x206f: // NOMINAL DIGIT SHAPES
case 0xfeff: // ZERO WIDTH NO-BREAK SPACE
case 0xfff9: // INTERLINEAR ANNOTATION ANCHOR
case 0xfffa: // INTERLINEAR ANNOTATION SEPARATOR
case 0xfffb: // INTERLINEAR ANNOTATION TERMINATOR
c = read();
continue; // skip it.
default:
break;
}
break; // out of while loop.
}
if( c == 0x000a && prev_line.length()!=0 && prev_line.charAt(prev_line.length()-1) == 0x000d ) {
// If this is one of those funny double line terminators,
// Then ignore the second character by reading on.
line_breaks[lnNum] = pos; // adjust if forward.
c = read();
}
// Line terminators.
if( c == 0x000a ||
c == 0x000d ||
c == 0x2028 ||
c == 0x2029 ) {
curr_line.append((char)c);
c = '\n';
line_breaks[lnNum+1] = pos;
// White space
} else if( c == 0x0009 ||
c == 0x000b ||
c == 0x000c ||
c == 0x0020 ||
c == 0x00a0 ||
false /* other cat Zs' */ ) {
c = ' ';
curr_line.append((char)c);
// End of line
} else if( c == -1 ) {
c = 0;
curr_line.append((char)c);
// All other characters.
} else {
// Use c as is.
curr_line.append((char)c);
}
}
}
// Get the next character.
int ln = lnNum;
int col = colPos;
if( curr_line.length() != 0 && curr_line.charAt(colPos) == 0 ) {
c = 0;
colPos++;
} else if( colPos == curr_line.length()-1 ) {
c = '\n';
colPos++;
} else {
c = curr_line.charAt(colPos++);
}
if( out != null ) {
out.println("Ln " + ln + ", Col " + col + ": nextchar " + Integer.toHexString(c) + " = " + (char)c + " @ " + positionOfNext());
}
if( debug || debug_nextchar ) {
Debugger.trace("Ln " + ln + ", Col " + col + ": nextchar " + Integer.toHexString(c) + " = " + (char)c + " @ " + positionOfNext());
}
return c;
}
/**
* test_nextchar() --
* Return an indication of how nextchar() performs
* in various situations, relative to expectations.
*/
boolean test_nextchar() {
return true;
}
/**
* time_nextchar() --
* Return the milliseconds taken to do various ordinary
* tasks with nextchar().
*/
int time_nextchar() {
return 0;
}
/**
* retract
*
* Backup one character position in the input. If at the beginning
* of the line, then swap buffers and point to the last character
* in the other buffer.
*/
public final void retract() throws Exception {
colPos--;
if( colPos<0 ) {
if( curr_line == prev_line ) {
// Can only retract over one line.
throw new Exception("Can only retract past one line at a time.");
} else if( curr_line == lineA ) {
curr_line = lineB = prev_line;
} else {
curr_line = lineA = prev_line;
}
lnNum--;
colPos = curr_line.length()-1;
curr_line_offset = prev_line_offset;
}
if( debug || debug_retract ) {
Debugger.trace("Ln " + lnNum + ", Col " + colPos + ": retract");
}
return;
}
static boolean test_retract() {
Debugger.trace("test_retract");
Reader reader = new StringReader("abc\ndef\nghi");
try {
InputBuffer inbuf = new InputBuffer(reader,System.err,"test");
int c=-1;
for(int i=0;i<9;i++) {
c = inbuf.nextchar();
}
for(int i=0;i<3;i++) {
inbuf.retract();
c = inbuf.nextchar();
inbuf.retract();
}
while(c!=0) {
c = inbuf.nextchar();
}
} catch (Exception x) {
x.printStackTrace();
System.out.println(x);
}
return true;
}
/**
* classOfNext
*/
public byte classOfNext() {
// return the Unicode character class of the current
// character, which is pointed to by 'next-1'.
return CharacterClasses.data[curr_line.charAt(colPos-1)];
}
/**
* positionOfNext
*/
public int positionOfNext() {
return curr_line_offset+colPos-1;
}
/**
* positionOfMark
*/
public int positionOfMark() {
return line_breaks[markLn]+markCol-1;
}
/**
* mark
*/
int markCol;
int markLn;
public int mark() {
markLn = (lnNum==-1)?0:lnNum; // In case nextchar hasn't been called yet.
markCol = colPos;
if( debug ) {
Debugger.trace("Ln " + markLn + ", Col " + markCol + ": mark");
}
return markCol;
}
/**
* copy
*/
public String copy() throws Exception {
StringBuffer buf = new StringBuffer();
if( debug ) {
Debugger.trace("Ln " + lnNum + ", Col " + colPos + ": copy " + buf);
}
if(markLn!=lnNum || markCol>colPos) {
throw new Exception("Internal error: InputBuffer.copy() markLn = " + markLn + ", lnNum = " + lnNum + ", markCol = " +
markCol + ", colPos = " + colPos );
}
for (int i = markCol-1; i < colPos; i++) {
buf.append(curr_line.charAt(i));
}
return buf.toString();
}
static boolean test_markandcopy() {
Debugger.trace("test_copy");
Reader reader = new StringReader("abc\ndef\nghijklmnopqrst\nuvwxyz");
String s;
try {
InputBuffer inbuf = new InputBuffer(reader,System.err,"test");
int c=-1;
int i;
for(i=0;i<10;i++) {
c = inbuf.nextchar();
}
inbuf.mark();
for(;i<13;i++) {
c = inbuf.nextchar();
}
s = inbuf.copy();
if(s.equals("ijk")) {
Debugger.trace("1: passed: " + s);
} else {
Debugger.trace("1: failed: " + s);
}
while(c!=0) {
c = inbuf.nextchar();
}
s = inbuf.copy();
} catch (Exception x) {
s = x.getMessage();
//x.printStackTrace();
}
if(s.equals("Internal error: InputBuffer.copy() markLn = 2, lnNum = 3, markCol = 2, colPos = 6")) {
Debugger.trace("2: passed: " + s);
} else {
Debugger.trace("2: failed: " + s);
}
return true;
}
public String getLineText(int pos) {
int i,len;
for(i = 0; line_breaks[i] <= pos && i <= lnNum; i++)
;
int offset = line_breaks[i-1];
for(len = offset ; (text.charAt(len)!=(char)-1 &&
text.charAt(len)!=0x0a &&
text.charAt(len)!=0x0d &&
text.charAt(len)!=0x2028 &&
text.charAt(len)!=0x2029) ; len++) {
}
return text.substring(offset,len);
}
static boolean test_getLineText() {
Debugger.trace("test_getLineText");
Reader reader = new StringReader("abc\ndef\nghi");
try {
InputBuffer inbuf = new InputBuffer(reader,System.err,"test");
int c=-1;
for(int i=0;i<9;i++) {
c = inbuf.nextchar();
}
for(int i=0;i<3;i++) {
inbuf.retract();
c = inbuf.nextchar();
inbuf.retract();
}
while(c!=0) {
c = inbuf.nextchar();
}
for(int i=0;i<inbuf.text.length()-1;i++) {
Debugger.trace("text @ " + i + " " + inbuf.getLineText(i));
}
} catch (Exception x) {
x.printStackTrace();
System.out.println(x);
}
return true;
}
public int getColPos(int pos) {
Debugger.trace("pos " + pos);
int i,len;
for(i = 0; line_breaks[i] <= pos && i <= lnNum; i++)
;
int offset = line_breaks[i-1];
Debugger.trace("offset " + offset);
return pos-offset;
}
public int getLnNum(int pos) {
int i;
for(i = 0; line_breaks[i] <= pos && i <= lnNum; i++)
;
return i-1;
}
#endif
}
}
/*
* Copyright (c) 1998-2001 by Mountain View Compiler Company.
* All Rights Reserved.
*/

View File

@@ -0,0 +1,496 @@
#ifndef InputBuffer_h
#define InputBuffer_h
/*
* InputBuffer - filters and buffers characters from a Reader.
*/
#include <string>
#include <vector>
#include <iostream.h>
#include <sstream>
#include <stdio.h>
#include <fstream>
#include "characterclasses.h"
namespace esc {
namespace v1 {
using namespace CharacterClasses;
class InputBuffer {
public:
std::string* lineA;// = new StringBuffer();
std::string* lineB; // = new StringBuffer();
std::string* curr_line;
std::string* prev_line;
int curr_line_offset,prev_line_offset;
int lineA_offset, lineB_offset;
private:
std::string text;
std::vector<int> line_breaks; // = new int[1000];
std::ofstream* out;
public:
std::istream& in;
std::ostream& err;
std::string& origin;
int pos;
int colPos, lnNum; // <0,0> is the position of the first character.
/*
void setOut(std::string filename) {
out = new std::ofstream(filename,std::ios::binary);
}
*/
static void main(int argc, char* argv[]) {
test_retract();
test_markandcopy();
test_getLineText();
}
InputBuffer( std::istream& in, std::ostream& err, std::string& origin )
: lineA(new std::string()), lineB(new std::string()), curr_line(0), prev_line(0), in(in), err(err),
origin(origin), pos(0), lnNum(-1), colPos(0) {
line_breaks.resize(1000,0);
}
InputBuffer( std::istream& in, std::ostream& err, std::string& origin, int pos )
: lineA(new std::string()), lineB(new std::string()), curr_line(0), prev_line(0), in(in), err(err),
origin(origin), pos(pos), lnNum(-1), colPos(0) {
line_breaks.resize(1000,0);
}
/*
* read()
*
* Read the next character from the input reader and store it in a buffer
* of the full text.
*/
int read() {
int c = in.get();
text.insert(text.end(),(unsigned short)c);
pos++;
return c;
}
/*
* text()
*/
std::string& source() {
return text;
}
/*
* nextchar() --
*
* The basic function of nextchar() is to fetch the next character,
* in the input array, increment next and return the fetched character.
*
* To simplify the Scanner, this method also does the following:
* 1. normalizes certain special characters to a common character.
* 2. skips unicode format control characters (category Cf).
* 3. keeps track of line breaks, line position and line number.
* 4. treats <cr>+<lf> as a single line terminator.
* 5. returns 0 when the end of input is reached.
*/
int nextchar() {
int c = -1;
// If the last character was at the end of a line,
// then swap buffers and fill the new one with characters
// from the input reader.
if( curr_line==0 || colPos==curr_line->size() ) {
lnNum++;
colPos=0;
// If the current character is a newline, then read
// the next line of input into the other input buffer.
if( curr_line == lineA ) {
if( lineB == 0 ) {
lineB = new std::string();
lineB_offset = pos;
}
curr_line = lineB; curr_line_offset = lineB_offset;
prev_line = lineA; prev_line_offset = lineA_offset;
lineA = 0;
} else {
if( lineA == 0 ) {
lineA = new std::string();
lineA_offset = pos;
}
curr_line = lineA; curr_line_offset = lineA_offset;
prev_line = lineB; prev_line_offset = lineB_offset;
lineB = 0;
}
while(c != '\n' && c != 0) {
c = read();
if( false ) {
//Debugger.trace( "c = " + c );
}
// Skip Unicode 3.0 format-control (general category Cf in
// Unicode Character Database) characters.
while(true) {
switch(c) {
case 0x070f: // SYRIAC ABBREVIATION MARK
case 0x180b: // MONGOLIAN FREE VARIATION SELECTOR ONE
case 0x180c: // MONGOLIAN FREE VARIATION SELECTOR TWO
case 0x180d: // MONGOLIAN FREE VARIATION SELECTOR THREE
case 0x180e: // MONGOLIAN VOWEL SEPARATOR
case 0x200c: // ZERO WIDTH NON-JOINER
case 0x200d: // ZERO WIDTH JOINER
case 0x200e: // LEFT-TO-RIGHT MARK
case 0x200f: // RIGHT-TO-LEFT MARK
case 0x202a: // LEFT-TO-RIGHT EMBEDDING
case 0x202b: // RIGHT-TO-LEFT EMBEDDING
case 0x202c: // POP DIRECTIONAL FORMATTING
case 0x202d: // LEFT-TO-RIGHT OVERRIDE
case 0x202e: // RIGHT-TO-LEFT OVERRIDE
case 0x206a: // INHIBIT SYMMETRIC SWAPPING
case 0x206b: // ACTIVATE SYMMETRIC SWAPPING
case 0x206c: // INHIBIT ARABIC FORM SHAPING
case 0x206d: // ACTIVATE ARABIC FORM SHAPING
case 0x206e: // NATIONAL DIGIT SHAPES
case 0x206f: // NOMINAL DIGIT SHAPES
case 0xfeff: // ZERO WIDTH NO-BREAK SPACE
case 0xfff9: // INTERLINEAR ANNOTATION ANCHOR
case 0xfffa: // INTERLINEAR ANNOTATION SEPARATOR
case 0xfffb: // INTERLINEAR ANNOTATION TERMINATOR
c = read();
continue; // skip it.
default:
break;
}
break; // out of while loop.
}
if( c == 0x000a && prev_line->size()!=0 && (*prev_line)[prev_line->size()-1] == (unsigned short)0x000d ) {
// If this is one of those funny double line terminators,
// Then ignore the second character by reading on.
line_breaks[lnNum]=pos; // adjust if forward.
c = read();
}
// Line terminators.
if( c == 0x000a ||
c == 0x000d ||
c == 0x2028 ||
c == 0x2029 ) {
curr_line->insert(curr_line->end(),(char)c);
c = '\n';
line_breaks[lnNum+1]=pos;
// White space
} else if( c == 0x0009 ||
c == 0x000b ||
c == 0x000c ||
c == 0x0020 ||
c == 0x00a0 ||
false /* other cat Zs' */ ) {
c = ' ';
curr_line->insert(curr_line->end(),(char)c);
// End of line
} else if( c == -1 ) {
c = 0;
curr_line->insert(curr_line->end(),(char)c);
// All other characters.
} else {
// Use c as is.
curr_line->insert(curr_line->end(),(char)c);
}
}
}
// Get the next character.
int ln = lnNum;
int col = colPos;
if( curr_line->size()!=0 && (*curr_line)[colPos] == 0 ) {
c = 0;
colPos++;
} else if( colPos == curr_line->size()-1 ) {
c = '\n';
colPos++;
} else {
c = (*curr_line)[colPos++];
}
if( out ) {
//out.println("Ln " + ln + ", Col " + col + ": nextchar " + Integer.toHexString(c) + " = " + (char)c + " @ " + positionOfNext());
}
//if( debug || debug_nextchar ) {
//Debugger.trace("Ln " + ln + ", Col " + col + ": nextchar " + Integer.toHexString(c) + " = " + (char)c + " @ " + positionOfNext());
//}
return c;
}
/**
* test_nextchar() --
* Return an indication of how nextchar() performs
* in various situations, relative to expectations.
*/
bool test_nextchar() {
return true;
}
/**
* time_nextchar() --
* Return the milliseconds taken to do various ordinary
* tasks with nextchar().
*/
int time_nextchar() {
return 0;
}
/**
* retract
*
* Backup one character position in the input. If at the beginning
* of the line, then swap buffers and point to the last character
* in the other buffer.
*/
void retract() {
colPos--;
if( colPos<0 ) {
if( curr_line == prev_line ) {
// Can only retract over one line.
throw; // new Exception("Can only retract past one line at a time.");
} else if( curr_line == lineA ) {
curr_line = lineB = prev_line;
} else {
curr_line = lineA = prev_line;
}
lnNum--;
colPos = curr_line->size()-1;
curr_line_offset = prev_line_offset;
}
//if( debug || debug_retract ) {
//Debugger.trace("Ln " + lnNum + ", Col " + colPos + ": retract");
//}
return;
}
static bool test_retract() {
//Debugger.trace("test_retract");
std::istringstream input("abc\ndef\nghi");
std::ofstream err("test.err");
std::string name("test");
InputBuffer* inbuf = new InputBuffer(input,err,name);
int c=-1;
int i;
for(i=0;i<9;i++) {
c = inbuf->nextchar();
}
for(i=0;i<3;i++) {
inbuf->retract();
c = inbuf->nextchar();
inbuf->retract();
}
while(c!=0) {
c = inbuf->nextchar();
}
return true;
}
/**
* classOfNext
*/
unsigned char classOfNext() {
// return the Unicode character class of the current
// character, which is pointed to by 'next-1'.
return CharacterClasses::data[curr_line->at(colPos-1)];
}
/**
* positionOfNext
*/
int positionOfNext() {
return curr_line_offset+colPos-1;
}
/**
* positionOfMark
*/
int positionOfMark() {
return line_breaks[markLn]+markCol;
}
/**
* mark
*/
int markCol;
int markLn;
int mark() {
markLn = (lnNum==-1)?0:lnNum; // In case nextchar hasn't been called yet.
markCol = colPos;
//if( debug ) {
// Debugger.trace("Ln " + markLn + ", Col " + markCol + ": mark");
//}
return markCol;
}
/*
* copy
*/
std::string* copy() {
std::string* buf = new std::string();
//if( debug ) {
// Debugger.trace("Ln " + lnNum + ", Col " + colPos + ": copy " + buf);
//}
if(markLn!=lnNum || markCol>colPos) {
throw; // new Exception("Internal error: InputBuffer.copy() markLn = " + markLn + ", lnNum = " + lnNum + ", markCol = " +
// markCol + ", colPos = " + colPos );
}
for (int i = markCol-1; i < colPos; i++) {
buf->insert(buf->end(),curr_line->at(i));
}
return buf;
}
static bool test_markandcopy() {
std::istringstream input("abc\ndef\nghijklmnopqrst\nuvwxyz");
std::string name("test");
std::ofstream err("test.err");
InputBuffer* inbuf = new InputBuffer(input,err,name);
std::string* s;
int c=-1;
int i;
for(i=0;i<10;i++) {
c = inbuf->nextchar();
}
inbuf->mark();
for(;i<13;i++) {
c = inbuf->nextchar();
}
s = inbuf->copy();
if( *s == "ijk") {
printf("1: passed: %s\n", s->c_str());
} else {
printf("1: failed: %s\n", s->c_str());
}
return true;
}
std::string getLineText(int pos) {
int i,len,a;
for(i = 0; (a=line_breaks.at(i)) <= pos && i <= lnNum; i++)
;
int offset = line_breaks.at(i-1);
for(len = offset ; (text.at(len)!=(char)-1 &&
text.at(len)!=0x0a &&
text.at(len)!=0x0d &&
text.at(len)!=0x2028 &&
text.at(len)!=0x2029) ; len++) {
}
std::string buf = std::string(len+1,0);
int count = text.copy(buf.begin(),len-offset,offset);
return buf;
}
static bool test_getLineText() {
std::istringstream input("abc\ndef\nghi");
std::string name("test");
std::ofstream err("test.err");
InputBuffer* inbuf = new InputBuffer(input,err,name);
int c=-1;
int i;
for(i=0;i<9;i++) {
c = inbuf->nextchar();
}
for(i=0;i<3;i++) {
inbuf->retract();
c = inbuf->nextchar();
inbuf->retract();
}
while(c!=0) {
c = inbuf->nextchar();
}
for(i=0;i<inbuf->text.length()-1;i++) {
std::string buf = inbuf->getLineText(i);
printf("text @ %d: %s\n",i,buf.c_str());
}
return true;
}
int getColPos(int pos) {
//Debugger.trace("pos " + pos);
int i;
for(i = 0; line_breaks.at(i) <= pos && i <= lnNum; i++)
;
int offset = line_breaks.at(i-1);
//Debugger.trace("offset " + offset);
return pos-offset;
}
int getLnNum(int pos) {
int i;
for(i = 0; line_breaks.at(i) <= pos && i <= lnNum; i++)
;
return i-1;
}
};
}
}
#endif // InputBuffer_h
/*
* Written by Jeff Dyer
* Copyright (c) 1998-2001 by Mountain View Compiler Company.
* All Rights Reserved.
*/

View File

@@ -0,0 +1,10 @@
#include "Token.h"
#include "States.h"
#include "Scanner.h"
namespace esc {
namespace v1 {
namespace lexer {
int Scanner::failureCount;
}}}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,403 @@
#ifndef States_h
#define States_h
#include <string>
namespace esc {
namespace v1 {
namespace lexer {
enum {
start_state = 0,
error_state = start_state-1,
minusminus_state = start_state+1,
minusequal_state = minusminus_state+1,
minus_state = minusequal_state+1,
notequal_state = minus_state+1,
not_state = notequal_state+1,
remainderequal_state = not_state+1,
remainder_state = remainderequal_state+1,
logicaland_state = remainder_state+1,
logicalandassign_state = logicaland_state+1,
andequal_state = logicalandassign_state+1,
and_state = andequal_state+1,
leftparen_state = and_state+1,
rightparen_state = leftparen_state+1,
starequal_state = rightparen_state+1,
star_state = starequal_state+1,
comma_state = star_state+1,
dot_state = comma_state+1,
doubledot_state = dot_state+1,
tripledot_state = doubledot_state+1,
slashequal_state = tripledot_state+1,
slash_state = slashequal_state+1,
colon_state = slash_state+1,
doublecolon_state = colon_state+1,
semicolon_state = doublecolon_state+1,
questionmark_state = semicolon_state+1,
leftbracket_state = questionmark_state+1,
rightbracket_state = leftbracket_state+1,
bitwisexorassign_state = rightbracket_state+1,
bitwisexor_state = bitwisexorassign_state+1,
logicalxor_state = bitwisexor_state+1,
logicalxorassign_state = logicalxor_state+1,
leftbrace_state = logicalxorassign_state+1,
logicalor_state = leftbrace_state+1,
logicalorassign_state = logicalor_state+1,
orequal_state = logicalorassign_state+1,
or_state = orequal_state+1,
rightbrace_state = or_state+1,
squiggle_state = rightbrace_state+1,
plusplus_state = squiggle_state+1,
plusequal_state = plusplus_state+1,
plus_state = plusequal_state+1,
leftshiftequal_state = plus_state+1,
leftshift_state = leftshiftequal_state+1,
lessthanorequal_state = leftshift_state+1,
lessthan_state = lessthanorequal_state+1,
equal_state = lessthan_state+1,
equalequal_state = equal_state+1,
greaterthanorequal_state = equalequal_state+1,
rightshiftequal_state = greaterthanorequal_state+1,
unsignedrightshift_state = rightshiftequal_state+1,
unsignedrightshiftequal_state = unsignedrightshift_state+1,
rightshift_state = unsignedrightshiftequal_state+1,
greaterthan_state = rightshift_state+1,
A_state = greaterthan_state+1,
N_state = A_state+1,
AA_state = N_state+1,
AN_state = AA_state+1,
singlequote_state = AN_state+1,
doublequote_state = singlequote_state+1,
zero_state = doublequote_state+1,
decimalinteger_state = zero_state+1,
decimal_state = decimalinteger_state+1,
exponent_state = decimal_state+1,
hexinteger_state = exponent_state+1,
octalinteger_state = hexinteger_state+1,
slashregexp_state = octalinteger_state+1,
slashdiv_state = slashregexp_state+1,
regexp_state = slashdiv_state+1,
regexpg_state = regexp_state+1,
regexpi_state = regexpg_state+1,
regexpm_state = regexpi_state+1,
regexpgi_state = regexpm_state+1,
regexpgm_state = regexpgi_state+1,
regexpim_state = regexpgm_state+1,
regexpgim_state = regexpim_state+1,
pound_state = regexpgim_state+1,
ampersand_state = pound_state+1,
arrow_state = ampersand_state+1,
a_state = arrow_state+1,
ab_state = a_state+1,
abs_state = ab_state+1,
abst_state = abs_state+1,
abstr_state = abst_state+1,
abstra_state = abstr_state+1,
abstrac_state = abstra_state+1,
abstract_state = abstrac_state+1,
at_state = abstract_state+1,
att_state = at_state+1,
attr_state = att_state+1,
attri_state = attr_state+1,
attrib_state = attri_state+1,
attribu_state = attrib_state+1,
attribut_state = attribu_state+1,
attribute_state = attribut_state+1,
b_state = attribute_state+1,
bo_state = b_state+1,
boo_state = bo_state+1,
bool_state = boo_state+1,
boole_state = bool_state+1,
boolea_state = boole_state+1,
boolean_state = boolea_state+1,
br_state = boolean_state+1,
bre_state = br_state+1,
brea_state = bre_state+1,
break_state = brea_state+1,
by_state = break_state+1,
byt_state = by_state+1,
byte_state = byt_state+1,
c_state = byte_state+1,
ca_state = c_state+1,
cas_state = ca_state+1,
case_state = cas_state+1,
cat_state = case_state+1,
catc_state = cat_state+1,
catch_state = catc_state+1,
ch_state = catch_state+1,
cha_state = ch_state+1,
char_state = cha_state+1,
cl_state = char_state+1,
cla_state = cl_state+1,
clas_state = cla_state+1,
class_state = clas_state+1,
co_state = class_state+1,
con_state = co_state+1,
cont_state = con_state+1,
conti_state = cont_state+1,
contin_state = conti_state+1,
continu_state = contin_state+1,
continue_state = continu_state+1,
cons_state = continue_state+1,
const_state = cons_state+1,
constr_state = const_state+1,
constru_state = constr_state+1,
construc_state = constru_state+1,
construct_state = construc_state+1,
constructo_state = construct_state+1,
constructor_state = constructo_state+1,
d_state = constructor_state+1,
de_state = d_state+1,
deb_state = de_state+1,
debu_state = deb_state+1,
debug_state = debu_state+1,
debugg_state = debug_state+1,
debugge_state = debugg_state+1,
debugger_state = debugge_state+1,
def_state = debugger_state+1,
defa_state = def_state+1,
defau_state = defa_state+1,
defaul_state = defau_state+1,
default_state = defaul_state+1,
del_state = default_state+1,
dele_state = del_state+1,
delet_state = dele_state+1,
delete_state = delet_state+1,
do_state = delete_state+1,
dou_state = do_state+1,
doub_state = dou_state+1,
doubl_state = doub_state+1,
double_state = doubl_state+1,
e_state = double_state+1,
el_state = e_state+1,
els_state = el_state+1,
else_state = els_state+1,
en_state = else_state+1,
enu_state = en_state+1,
enum_state = enu_state+1,
ev_state = enum_state+1,
eva_state = ev_state+1,
eval_state = eva_state+1,
ex_state = eval_state+1,
exc_state = ex_state+1,
excl_state = exc_state+1,
exclu_state = excl_state+1,
exclud_state = exclu_state+1,
exclude_state = exclud_state+1,
exp_state = exclude_state+1,
expo_state = exp_state+1,
expor_state = expo_state+1,
export_state = expor_state+1,
ext_state = export_state+1,
exte_state = ext_state+1,
exten_state = exte_state+1,
extend_state = exten_state+1,
extends_state = extend_state+1,
f_state = extends_state+1,
fa_state = f_state+1,
fal_state = fa_state+1,
fals_state = fal_state+1,
false_state = fals_state+1,
fi_state = false_state+1,
fin_state = fi_state+1,
fina_state = fin_state+1,
final_state = fina_state+1,
finall_state = final_state+1,
finally_state = finall_state+1,
fl_state = finally_state+1,
flo_state = fl_state+1,
floa_state = flo_state+1,
float_state = floa_state+1,
fo_state = float_state+1,
for_state = fo_state+1,
fu_state = for_state+1,
fun_state = fu_state+1,
func_state = fun_state+1,
funct_state = func_state+1,
functi_state = funct_state+1,
functio_state = functi_state+1,
function_state = functio_state+1,
g_state = function_state+1,
go_state = g_state+1,
got_state = go_state+1,
goto_state = got_state+1,
i_state = goto_state+1,
if_state = i_state+1,
im_state = if_state+1,
imp_state = im_state+1,
impl_state = imp_state+1,
imple_state = impl_state+1,
implem_state = imple_state+1,
impleme_state = implem_state+1,
implemen_state = impleme_state+1,
implement_state = implemen_state+1,
implements_state = implement_state+1,
impo_state = implements_state+1,
impor_state = impo_state+1,
import_state = impor_state+1,
in_state = import_state+1,
inc_state = in_state+1,
incl_state = inc_state+1,
inclu_state = incl_state+1,
includ_state = inclu_state+1,
include_state = includ_state+1,
ins_state = include_state+1,
inst_state = ins_state+1,
insta_state = inst_state+1,
instan_state = insta_state+1,
instanc_state = instan_state+1,
instance_state = instanc_state+1,
instanceo_state = instance_state+1,
instanceof_state = instanceo_state+1,
int_state = instanceof_state+1,
inte_state = int_state+1,
inter_state = inte_state+1,
interf_state = inter_state+1,
interfa_state = interf_state+1,
interfac_state = interfa_state+1,
interface_state = interfac_state+1,
l_state = interface_state+1,
lo_state = l_state+1,
lon_state = lo_state+1,
long_state = lon_state+1,
n_state = long_state+1,
na_state = n_state+1,
nam_state = na_state+1,
name_state = nam_state+1,
names_state = name_state+1,
namesp_state = names_state+1,
namespa_state = namesp_state+1,
namespac_state = namespa_state+1,
namespace_state = namespac_state+1,
nat_state = namespace_state+1,
nati_state = nat_state+1,
nativ_state = nati_state+1,
native_state = nativ_state+1,
ne_state = native_state+1,
new_state = ne_state+1,
nu_state = new_state+1,
nul_state = nu_state+1,
null_state = nul_state+1,
r_state = null_state+1,
re_state = r_state+1,
ret_state = re_state+1,
retu_state = ret_state+1,
retur_state = retu_state+1,
return_state = retur_state+1,
p_state = return_state+1,
pa_state = p_state+1,
pac_state = pa_state+1,
pack_state = pac_state+1,
packa_state = pack_state+1,
packag_state = packa_state+1,
package_state = packag_state+1,
pr_state = package_state+1,
pri_state = pr_state+1,
priv_state = pri_state+1,
priva_state = priv_state+1,
privat_state = priva_state+1,
private_state = privat_state+1,
pro_state = private_state+1,
prot_state = pro_state+1,
prote_state = prot_state+1,
protec_state = prote_state+1,
protect_state = protec_state+1,
protecte_state = protect_state+1,
protected_state = protecte_state+1,
pu_state = protected_state+1,
pub_state = pu_state+1,
publ_state = pub_state+1,
publi_state = publ_state+1,
public_state = publi_state+1,
s_state = public_state+1,
sh_state = s_state+1,
sho_state = sh_state+1,
shor_state = sho_state+1,
short_state = shor_state+1,
st_state = short_state+1,
sta_state = st_state+1,
stat_state = sta_state+1,
stati_state = stat_state+1,
static_state = stati_state+1,
su_state = static_state+1,
sup_state = su_state+1,
supe_state = sup_state+1,
super_state = supe_state+1,
sw_state = super_state+1,
swi_state = sw_state+1,
swit_state = swi_state+1,
switc_state = swit_state+1,
switch_state = switc_state+1,
sy_state = switch_state+1,
syn_state = sy_state+1,
sync_state = syn_state+1,
synch_state = sync_state+1,
synchr_state = synch_state+1,
synchro_state = synchr_state+1,
synchron_state = synchro_state+1,
synchroni_state = synchron_state+1,
synchroniz_state = synchroni_state+1,
synchronize_state = synchroniz_state+1,
synchronized_state = synchronize_state+1,
t_state = synchronized_state+1,
th_state = t_state+1,
thi_state = th_state+1,
this_state = thi_state+1,
thr_state = this_state+1,
thro_state = thr_state+1,
throw_state = thro_state+1,
throws_state = throw_state+1,
tr_state = throws_state+1,
tra_state = tr_state+1,
tran_state = tra_state+1,
trans_state = tran_state+1,
transi_state = trans_state+1,
transie_state = transi_state+1,
transien_state = transie_state+1,
transient_state = transien_state+1,
tru_state = transient_state+1,
true_state = tru_state+1,
try_state = true_state+1,
ty_state = try_state+1,
typ_state = ty_state+1,
type_state = typ_state+1,
typeo_state = type_state+1,
typeof_state = typeo_state+1,
u_state = typeof_state+1,
us_state = u_state+1,
use_state = us_state+1,
v_state = use_state+1,
va_state = v_state+1,
var_state = va_state+1,
vo_state = var_state+1,
vol_state = vo_state+1,
vola_state = vol_state+1,
volat_state = vola_state+1,
volati_state = volat_state+1,
volatil_state = volati_state+1,
volatile_state = volatil_state+1,
voi_state = volatile_state+1,
void_state = voi_state+1,
w_state = void_state+1,
wh_state = w_state+1,
whi_state = wh_state+1,
whil_state = whi_state+1,
while_state = whil_state+1,
wi_state = while_state+1,
wit_state = wi_state+1,
with_state = wit_state+1,
blockcomment_state = with_state+1,
blockcommentstar_state = blockcomment_state+1,
linecomment_state = blockcommentstar_state+1,
eol_state = linecomment_state+1,
};
}
}
}
#endif // States_h

View File

@@ -0,0 +1,79 @@
#ifndef Token_h
#define Token_h
#include <string>
#include "Tokens.h"
namespace esc {
namespace v1 {
namespace lexer {
/*
* Represents token instances: literals and identifiers.
*
* This file implements the class Token that is used to carry
* information from the Scanner to the Parser.
*/
class Token {
int tokenClass;
std::string* lexeme;
public:
Token( int tokenClass, std::string* lexeme )
: tokenClass(tokenClass), lexeme(lexeme) {
}
int getTokenClass() {
return tokenClass;
}
/*
* Return a copy of the token text string. Caller deletes it.
*/
std::string getTokenText() {
if( tokenClass == stringliteral_token ) {
std::string buf = std::string(lexeme->length()-2,0);
// don't include quotes.
lexeme->copy(buf.begin(),lexeme->length()-2,1);
return buf;
}
return std::string(*lexeme);
}
std::string getTokenSource() {
return std::string(*lexeme);
}
static const std::string getTokenClassName( int token_class ) {
return tokenClassNames[-1*token_class];
}
/**
* main()
*
* Unit test driver. Execute the command 'java Token' at the
* shell to verify this class' basic functionality.
*/
static void main(int argc, char* args[]) {
printf("Token begin");
for(int i = 0; i>=stringliteral_token;i--) {
printf("%s=%d\n",tokenClassNames[-1*i].c_str(),i);
}
printf("Token end");
}
};
}
}
}
#endif // Token_h
/*
* The end.
*/

View File

@@ -0,0 +1,321 @@
/*
* Defines token classes and their print names.
*
* This interface defines values for each token class that occurs in
* ECMAScript 4. All but numericliteral, stringliteral, regexpliteral, and
* identifier are singleton and therefore a fully described by their
* token class defined here. The other four however can have an infinite number
* of instances each with a unique identifier and associated instance
* data. We use positive identifiers to signify instances of these
* token classes so that the instance data can be stored in an array,
* or set of arrays with the token value specifying its index.
*/
/**
* The base Node class.
*/
#ifndef Tokens_h
#define Tokens_h
#include <string>
namespace esc {
namespace v1 {
namespace lexer {
/*
* Token class values are negative, and token instances are positive so
* that their values can point to their instance data in an array.
*/
enum {
first_token = -1,
eos_token = first_token-0,
minus_token = first_token - 1,
minusminus_token = minus_token - 1,
not_token = minusminus_token - 1,
notequals_token = not_token - 1,
strictnotequals_token = notequals_token - 1,
pound_token = strictnotequals_token - 1,
modulus_token = pound_token - 1,
modulusassign_token = modulus_token - 1,
bitwiseand_token = modulusassign_token - 1,
logicaland_token = bitwiseand_token - 1,
logicalandassign_token = logicaland_token - 1,
bitwiseandassign_token = logicalandassign_token - 1,
leftparen_token = bitwiseandassign_token - 1,
rightparen_token = leftparen_token - 1,
mult_token = rightparen_token - 1,
multassign_token = mult_token - 1,
comma_token = multassign_token - 1,
dot_token = comma_token - 1,
doubledot_token = dot_token - 1,
tripledot_token = doubledot_token - 1,
div_token = tripledot_token - 1,
divassign_token = div_token - 1,
colon_token = divassign_token - 1,
doublecolon_token = colon_token - 1,
semicolon_token = doublecolon_token - 1,
questionmark_token = semicolon_token - 1,
ampersand_token = questionmark_token - 1,
leftbracket_token = ampersand_token - 1,
rightbracket_token = leftbracket_token - 1,
bitwisexor_token = rightbracket_token - 1,
logicalxor_token = bitwisexor_token - 1,
logicalxorassign_token = logicalxor_token - 1,
bitwisexorassign_token = logicalxorassign_token - 1,
leftbrace_token = bitwisexorassign_token - 1,
bitwiseor_token = leftbrace_token - 1,
logicalor_token = bitwiseor_token - 1,
logicalorassign_token = logicalor_token - 1,
bitwiseorassign_token = logicalorassign_token - 1,
rightbrace_token = bitwiseorassign_token - 1,
bitwisenot_token = rightbrace_token - 1,
plus_token = bitwisenot_token - 1,
plusplus_token = plus_token - 1,
plusassign_token = plusplus_token - 1,
lessthan_token = plusassign_token - 1,
leftshift_token = lessthan_token - 1,
leftshiftassign_token = leftshift_token - 1,
lessthanorequals_token = leftshiftassign_token - 1,
assign_token = lessthanorequals_token - 1,
minusassign_token = assign_token - 1,
equals_token = minusassign_token - 1,
strictequals_token = equals_token - 1,
greaterthan_token = strictequals_token - 1,
arrow_token = greaterthan_token - 1,
greaterthanorequals_token = arrow_token - 1,
rightshift_token = greaterthanorequals_token - 1,
rightshiftassign_token = rightshift_token - 1,
unsignedrightshift_token = rightshiftassign_token - 1,
unsignedrightshiftassign_token = unsignedrightshift_token - 1,
abstract_token = unsignedrightshiftassign_token - 1,
attribute_token = abstract_token - 1,
boolean_token = attribute_token - 1,
break_token = boolean_token - 1,
byte_token = break_token - 1,
case_token = byte_token - 1,
catch_token = case_token - 1,
char_token = catch_token - 1,
class_token = char_token - 1,
const_token = class_token - 1,
constructor_token = const_token - 1,
continue_token = constructor_token - 1,
debugger_token = continue_token - 1,
default_token = debugger_token - 1,
delete_token = default_token - 1,
do_token = delete_token - 1,
double_token = do_token - 1,
else_token = double_token - 1,
enum_token = else_token - 1,
eval_token = enum_token - 1,
exclude_token = eval_token - 1,
export_token = exclude_token - 1,
extends_token = export_token - 1,
false_token = extends_token - 1,
final_token = false_token - 1,
finally_token = final_token - 1,
float_token = finally_token - 1,
for_token = float_token - 1,
function_token = for_token - 1,
get_token = function_token - 1,
goto_token = get_token - 1,
if_token = goto_token - 1,
implements_token = if_token - 1,
import_token = implements_token - 1,
in_token = import_token - 1,
include_token = in_token - 1,
instanceof_token = include_token - 1,
int_token = instanceof_token - 1,
interface_token = int_token - 1,
long_token = interface_token - 1,
namespace_token = long_token - 1,
native_token = namespace_token - 1,
new_token = native_token - 1,
null_token = new_token - 1,
package_token = null_token - 1,
private_token = package_token - 1,
protected_token = private_token - 1,
public_token = protected_token - 1,
return_token = public_token - 1,
set_token = return_token - 1,
short_token = set_token - 1,
static_token = short_token - 1,
super_token = static_token - 1,
switch_token = super_token - 1,
synchronized_token = switch_token - 1,
this_token = synchronized_token - 1,
throw_token = this_token - 1,
throws_token = throw_token - 1,
transient_token = throws_token - 1,
true_token = transient_token - 1,
try_token = true_token - 1,
typeof_token = try_token - 1,
use_token = typeof_token - 1,
var_token = use_token - 1,
void_token = var_token - 1,
volatile_token = void_token - 1,
while_token = volatile_token - 1,
with_token = while_token - 1,
identifier_token = with_token - 1,
numberliteral_token = identifier_token - 1,
regexpliteral_token = numberliteral_token - 1,
stringliteral_token = regexpliteral_token - 1,
eol_token = stringliteral_token - 1,
empty_token = eol_token - 1,
error_token = empty_token - 1,
last_token = empty_token - 1,
};
}
const std::string tokenClassNames [] = {
"<unused index>",
"<eos>",
"minus_token",
"minusminus_token",
"not_token",
"notequals_token",
"strictnotequals_token",
"pound_token",
"modulus_token",
"modulusassign_token",
"bitwiseand_token",
"logicaland_token",
"logicalandassign_token",
"bitwiseandassign_token",
"leftparen_token",
"rightparen_token",
"mult_token",
"multassign_token",
"comma_token",
"dot_token",
"doubledot_token",
"tripledot_token",
"div_token",
"divassign_token",
"colon_token",
"doublecolon_token",
"semicolon_token",
"questionmark_token",
"ampersand_token",
"leftbracket_token",
"rightbracket_token",
"bitwisexor_token",
"logicalxor_token",
"logicalxorassign_token",
"bitwisexorassign_token",
"leftbrace_token",
"bitwiseor_token",
"logicalor_token",
"logicalorassign_token",
"bitwiseorassign_token",
"rightbrace_token",
"bitwisenot_token",
"plus_token",
"plusplus_token",
"plusassign_token",
"lessthan_token",
"leftshift_token",
"leftshiftassign_token",
"lessthanorequals_token",
"assign_token",
"minusassign_token",
"equals_token",
"strictequals_token",
"greaterthan_token",
"arrow_token",
"greaterthanorequals_token",
"rightshift_token",
"rightshiftassign_token",
"unsignedrightshift_token",
"unsignedrightshiftassign_token",
"abstract_token",
"attribute_token",
"boolean_token",
"break_token",
"byte_token",
"case_token",
"catch_token",
"char_token",
"class_token",
"const_token",
"constructor_token",
"continue_token",
"debugger_token",
"default_token",
"delete_token",
"do_token",
"double_token",
"else_token",
"enum_token",
"eval_token",
"exclude_token",
"export_token",
"extends_token",
"false_token",
"final_token",
"finally_token",
"float_token",
"for_token",
"function_token",
"get_token",
"goto_token",
"if_token",
"implements_token",
"import_token",
"in_token",
"include_token",
"instanceof_token",
"int_token",
"interface_token",
"long_token",
"namespace_token",
"native_token",
"new_token",
"null_token",
"package_token",
"private_token",
"protected_token",
"public_token",
"return_token",
"set_token",
"short_token",
"static_token",
"super_token",
"switch_token",
"synchronized_token",
"this_token",
"throw_token",
"throws_token",
"transient_token",
"true_token",
"try_token",
"typeof_token",
"use_token",
"var_token",
"void_token",
"volatile_token",
"while_token",
"with_token",
"identifier_token",
"numberliteral_token",
"regexpliteral_token",
"stringliteral_token",
"<eol>",
"<empty>",
"<error>"
};
}
}
#endif // Tokens_h
/*
* The end.
*/

View File

@@ -0,0 +1,141 @@
// main.cpp : Defines the entry point for the console application.
//
#pragma warning( disable : 4786 )
#include <stdio.h>
#include <fstream>
#include "ByteCodeFactory.h"
#include "ObjectValue.h"
#include "ConstantEvaluator.h"
#include "NodeFactory.h"
#include "ClassFileGenerator.h"
#include "TypeValue.h"
#include "InputBuffer.h"
#include "Token.h"
#include "Scanner.h"
#include "Parser.h"
#include "Node.h"
#include "NodePrinter.h"
int main(int argc, char* argv[])
{
using namespace esc::v1;
using namespace esc::v1::parser;
printf("esc\n");
bool show_parsetrees = false;
bool do_test = false;
bool do_help = false;
std::string source;
if( argc == 1 ) {
++do_test;
} else {
for( int i = argc-1; i > 0; i-- ) {
char* flag = argv[i];
if(flag[0]=='-') {
switch(flag[1]) {
case 'p':
++show_parsetrees;
break;
case 'h':
default:
++do_help;
break;
}
} else {
source = argv[i];
}
}
}
if( do_help ) {
return 0;
}
TypeValue::init();
ObjectValue::init();
if( do_test ) {
std::ofstream dbg("test.dbg");
Debugger::init(&dbg);
InputBuffer::main(argc,argv);
InputBuffer::test_getLineText();
InputBuffer::test_markandcopy();
using namespace esc::v1::lexer;
Token::main(argc,argv);
Scanner::main(argc,argv);
NodeFactory::main(argc,argv);
using namespace esc::v1::parser;
Parser::main(argc,argv);
ConstantEvaluator::main(argc,argv);
ObjectValue::main(argc,argv);
ByteCodeFactory::main(argc,argv);
ClassFileGenerator::main(argc,argv);
} else {
// Init the subsystems
NodeFactory::init();
std::ifstream in = std::ifstream((source+".js").c_str());
std::ofstream err((source+".err").c_str());
std::ofstream dbg((source+".dbg").c_str());
Debugger::init(&dbg);
Context cx(err);
// Parse
Parser* parser = new Parser(in,err,source);
ProgramNode* node = parser->parseProgram();
if( show_parsetrees ) {
NodePrinter* printer = new NodePrinter();
node->evaluate(cx,printer);
cout << printer->str().c_str();
return 0;
}
// Analyze
ConstantEvaluator* analyzer = new ConstantEvaluator();
node->evaluate(cx,analyzer);
// Generate
ClassFileGenerator* generator = new ClassFileGenerator(source);
node->evaluate(cx,generator);
// Write the class file
std::vector<byte>& bytes=*new std::vector<byte>();
generator->emit(bytes); // Emit it
std::ofstream* of = new std::ofstream((source+".class").c_str(),std::ios::binary);
of->write(bytes.begin(),bytes.size());
// Clean up
delete generator; // Get rid of the generator after one use.
delete analyzer;
NodeFactory::clear();
}
ObjectValue::fini();
TypeValue::fini();
return 0;
}
/*
* Written by Jeff Dyer
* Copyright (c) 1998-2001 by Mountain View Compiler Company.
* All Rights Reserved.
*/

View File

@@ -0,0 +1,26 @@
/*
* Activation interface. An activation provides slot storage.
*/
#ifndef Builder_h
#define Builder_h
namespace esc {
namespace v1 {
class ObjectValue;
class Builder {
public:
virtual void build(Context& cx, ObjectValue* ob) = 0;
};
}
}
#endif // Builder_h
/*
* Copyright (c) 1998-2001 by Mountain View Compiler Company
* All rights reserved.
*/

View File

@@ -0,0 +1,174 @@
#pragma warning ( disable : 4786 )
#include <string>
#include "Context.h"
namespace esc {
namespace v1 {
std::map<std::string,std::string> Context::e3cp_profile;
std::map<std::string,std::string> Context::e4_profile;
void Context::init() {
if( e3cp_profile.size() == 0 ) {
//e3cp_profile["IdentifierNode"]="not supported";
//e3cp_profile["ThisExpressionNode"]="not supported";
e3cp_profile["SuperExpressionNode"]="not supported";
e3cp_profile["QualifiedIdentifierNode"]="not supported";
//e3cp_profile["LiteralNullNode"]="not supported";
//e3cp_profile["LiteralBooleanNode"]="not supported";
//e3cp_profile["LiteralNumberNode"]="not supported";
//e3cp_profile["LiteralStringNode"]="not supported";
//e3cp_profile["LiteralUndefinedNode"]="not supported";
e3cp_profile["LiteralRegExpNode"]="not supported";
e3cp_profile["UnitExpressionNode"]="not supported";
//e3cp_profile["FunctionExpressionNode"]="not supported";
//e3cp_profile["ParenthesizedExpressionNode"]="not supported";
//e3cp_profile["ParenthesizedListExpressionNode"]="not supported";
//e3cp_profile["LiteralObjectNode"]="not supported";
//e3cp_profile["LiteralFieldNode"]="not supported";
//e3cp_profile["LiteralArrayNode"]="not supported";
//e3cp_profile["PostfixExpressionNode"]="not supported";
//e3cp_profile["NewExpressionNode"]="not supported";
e3cp_profile["IndexedMemberExpressionNode"]="not supported";
e3cp_profile["ClassofExpressionNode"]="not supported";
//e3cp_profile["MemberExpressionNode"]="not supported";
//e3cp_profile["CoersionExpressionNode"]="not supported";
//e3cp_profile["CallExpressionNode"]="not supported";
//e3cp_profile["GetExpressionNode"]="not supported";
//e3cp_profile["SetExpressionNode"]="not supported";
//e3cp_profile["UnaryExpressionNode"]="not supported";
//e3cp_profile["BinaryExpressionNode"]="not supported";
//e3cp_profile["ConditionalExpressionNode"]="not supported";
//e3cp_profile["AssignmentExpressionNode"]="not supported";
//e3cp_profile["ListNode"]="not supported";
//e3cp_profile["StatementListNode"]="not supported";
//e3cp_profile["EmptyStatementNode"]="not supported";
//e3cp_profile["ExpressionStatementNode"]="not supported";
e3cp_profile["AnnotatedBlockNode"]="not supported";
e3cp_profile["LabeledStatementNode"]="not supported";
e3cp_profile["IfStatementNode"]="not supported";
e3cp_profile["SwitchStatementNode"]="not supported";
e3cp_profile["CaseLabelNode"]="not supported";
e3cp_profile["DoStatementNode"]="not supported";
e3cp_profile["WhileStatementNode"]="not supported";
e3cp_profile["ForInStatementNode"]="not supported";
e3cp_profile["ForStatementNode"]="not supported";
e3cp_profile["WithStatementNode"]="not supported";
e3cp_profile["ContinueStatementNode"]="not supported";
e3cp_profile["BreakStatementNode"]="not supported";
e3cp_profile["ReturnStatementNode"]="not supported";
e3cp_profile["ThrowStatementNode"]="not supported";
e3cp_profile["TryStatementNode"]="not supported";
e3cp_profile["CatchClauseNode"]="not supported";
e3cp_profile["FinallyClauseNode"]="not supported";
e3cp_profile["UseStatementNode"]="not supported";
e3cp_profile["IncludeStatementNode"]="not supported";
e3cp_profile["ImportDefinitionNode"]="not supported";
e3cp_profile["ImportBindingNode"]="not supported";
e3cp_profile["AnnotatedDefinitionNode"]="not supported";
e3cp_profile["AttributeListNode"]="not supported";
e3cp_profile["ExportDefinitionNode"]="not supported";
e3cp_profile["ExportBindingNode"]="not supported";
e3cp_profile["VariableDefinitionNode"]="not supported";
e3cp_profile["VariableBindingNode"]="not supported";
e3cp_profile["TypedVariableNode"]="not supported";
e3cp_profile["FunctionDefinitionNode"]="not supported";
e3cp_profile["FunctionDeclarationNode"]="not supported";
e3cp_profile["FunctionNameNode"]="not supported";
e3cp_profile["FunctionSignatureNode"]="not supported";
e3cp_profile["ParameterNode"]="not supported";
e3cp_profile["OptionalParameterNode"]="not supported";
e3cp_profile["RestParameterNode"]="not supported";
e3cp_profile["NamedParameterNode"]="not supported";
e3cp_profile["ClassDefinitionNode"]="not supported";
e3cp_profile["ClassDeclarationNode"]="not supported";
e3cp_profile["InheritanceNode"]="not supported";
e3cp_profile["NamespaceDefinitionNode"]="not supported";
e3cp_profile["PackageDefinitionNode"]="not supported";
e3cp_profile["LanguageDeclarationNode"]="not supported";
//e3cp_profile["ProgramNode"]="not supported";
}
if( e4_profile.size() == 0 ) {
//e4_profile["IdentifierNode"]="not implemented";
//e4_profile["ThisExpressionNode"]="not implemented";
//e4_profile["SuperExpressionNode"]="not implemented";
//e4_profile["QualifiedIdentifierNode"]="not implemented";
//e4_profile["LiteralNullNode"]="not implemented";
//e4_profile["LiteralBooleanNode"]="not implemented";
//e4_profile["LiteralNumberNode"]="not implemented";
//e4_profile["LiteralStringNode"]="not implemented";
//e4_profile["LiteralUndefinedNode"]="not implemented";
//e4_profile["LiteralRegExpNode"]="not implemented";
//e4_profile["UnitExpressionNode"]="not implemented";
//e4_profile["FunctionExpressionNode"]="not implemented";
//e4_profile["ParenthesizedExpressionNode"]="not implemented";
//e4_profile["ParenthesizedListExpressionNode"]="not implemented";
//e4_profile["LiteralObjectNode"]="not implemented";
//e4_profile["LiteralFieldNode"]="not implemented";
//e4_profile["LiteralArrayNode"]="not implemented";
//e4_profile["PostfixExpressionNode"]="not implemented";
//e4_profile["NewExpressionNode"]="not implemented";
//e4_profile["IndexedMemberExpressionNode"]="not implemented";
//e4_profile["ClassofExpressionNode"]="not implemented";
//e4_profile["MemberExpressionNode"]="not implemented";
//e4_profile["CoersionExpressionNode"]="not implemented";
//e4_profile["CallExpressionNode"]="not implemented";
//e4_profile["GetExpressionNode"]="not implemented";
//e4_profile["SetExpressionNode"]="not implemented";
//e4_profile["UnaryExpressionNode"]="not implemented";
//e4_profile["BinaryExpressionNode"]="not implemented";
//e4_profile["ConditionalExpressionNode"]="not implemented";
//e4_profile["AssignmentExpressionNode"]="not implemented";
//e4_profile["ListNode"]="not implemented";
//e4_profile["StatementListNode"]="not implemented";
//e4_profile["EmptyStatementNode"]="not implemented";
//e4_profile["ExpressionStatementNode"]="not implemented";
e4_profile["AnnotatedBlockNode"]="not implemented";
e4_profile["LabeledStatementNode"]="not implemented";
e4_profile["IfStatementNode"]="not implemented";
e4_profile["SwitchStatementNode"]="not implemented";
e4_profile["CaseLabelNode"]="not implemented";
e4_profile["DoStatementNode"]="not implemented";
e4_profile["WhileStatementNode"]="not implemented";
e4_profile["ForInStatementNode"]="not implemented";
e4_profile["ForStatementNode"]="not implemented";
e4_profile["WithStatementNode"]="not implemented";
e4_profile["ContinueStatementNode"]="not implemented";
e4_profile["BreakStatementNode"]="not implemented";
e4_profile["ReturnStatementNode"]="not implemented";
e4_profile["ThrowStatementNode"]="not implemented";
e4_profile["TryStatementNode"]="not implemented";
e4_profile["CatchClauseNode"]="not implemented";
e4_profile["FinallyClauseNode"]="not implemented";
e4_profile["UseStatementNode"]="not implemented";
e4_profile["IncludeStatementNode"]="not implemented";
e4_profile["ImportDefinitionNode"]="not implemented";
e4_profile["ImportBindingNode"]="not implemented";
e4_profile["AnnotatedDefinitionNode"]="not implemented";
e4_profile["AttributeListNode"]="not implemented";
e4_profile["ExportDefinitionNode"]="not implemented";
e4_profile["ExportBindingNode"]="not implemented";
e4_profile["VariableDefinitionNode"]="not implemented";
e4_profile["VariableBindingNode"]="not implemented";
e4_profile["TypedVariableNode"]="not implemented";
e4_profile["FunctionDefinitionNode"]="not implemented";
e4_profile["FunctionDeclarationNode"]="not implemented";
//e4_profile["FunctionNameNode"]="not implemented";
//e4_profile["FunctionSignatureNode"]="not implemented";
//e4_profile["ParameterNode"]="not implemented";
e4_profile["OptionalParameterNode"]="not implemented";
e4_profile["RestParameterNode"]="not implemented";
e4_profile["NamedParameterNode"]="not implemented";
e4_profile["ClassDefinitionNode"]="not implemented";
e4_profile["ClassDeclarationNode"]="not implemented";
e4_profile["InheritanceNode"]="not implemented";
e4_profile["NamespaceDefinitionNode"]="not implemented";
e4_profile["PackageDefinitionNode"]="not implemented";
e4_profile["LanguageDeclarationNode"]="not implemented";
//e4_profile["ProgramNode"]="not implemented";
}
}
}
}

View File

@@ -0,0 +1,81 @@
/*
* Execution context.
*/
#ifndef Context_h
#define Context_h
#include <stack>
#include <vector>
#include <fstream>
#include <map>
namespace esc {
namespace v1 {
class Value;
class ObjectValue;
class Context {
ObjectValue* global;
std::stack<ObjectValue*> scopes;
std::ofstream* err_root;
public:
static std::map<std::string,std::string> e3cp_profile;
static std::map<std::string,std::string> e4_profile;
std::map<std::string,std::string> features;
std::ofstream& err;
static void init();
Context(std::ofstream& err, const std::map<std::string,std::string>& features = e4_profile) : err(err), err_root(0), features(features) {
}
Context() : err(*(err_root=new std::ofstream("default.err"))) {
}
~Context() {
if( err_root ) {
delete err_root;
}
}
void pushScope(ObjectValue* scope) {
if(scopes.empty()) {
global = scope;
}
scopes.push(scope);
}
void popScope() {
scopes.pop();
}
std::stack<ObjectValue*> getScopes() {
return scopes;
}
ObjectValue* scope() {
return scopes.top();
}
ObjectValue* globalScope() {
return global;
}
std::vector<Value*> used_namespaces;
};
}
}
#endif // Context_h
/*
* Copyright (c) 1998-2001 by Mountain View Compiler Company
* All rights reserved.
*/

View File

@@ -0,0 +1,363 @@
/**
* The base visitor object extended by semantic evaluators.
*
* This is a visitor that is used by the compiler for various forms for
* evaluation of a parse tree (e.g. a type evaluator might compute the
* static type of an expression.)
*/
#ifndef Evaluator_h
#define Evaluator_h
#include <map>
#include "Value.h"
#include "Context.h"
#include "Node.h"
namespace esc {
namespace v1 {
struct Node;
struct IdentifierNode;
struct ThisExpressionNode;
struct SuperExpressionNode;
struct QualifiedIdentifierNode;
struct LiteralNullNode;
struct LiteralBooleanNode;
struct LiteralNumberNode;
struct LiteralStringNode;
struct LiteralUndefinedNode;
struct LiteralRegExpNode;
struct UnitExpressionNode;
struct FunctionExpressionNode;
struct ParenthesizedExpressionNode;
struct ParenthesizedListExpressionNode;
struct LiteralObjectNode;
struct LiteralFieldNode;
struct LiteralArrayNode;
struct PostfixExpressionNode;
struct NewExpressionNode;
struct IndexedMemberExpressionNode;
struct ClassofExpressionNode;
struct MemberExpressionNode;
struct CoersionExpressionNode;
struct CallExpressionNode;
struct GetExpressionNode;
struct SetExpressionNode;
struct UnaryExpressionNode;
struct BinaryExpressionNode;
struct ConditionalExpressionNode;
struct AssignmentExpressionNode;
struct ListNode;
struct StatementListNode;
struct EmptyStatementNode;
struct ExpressionStatementNode;
struct AnnotatedBlockNode;
struct LabeledStatementNode;
struct IfStatementNode;
struct SwitchStatementNode;
struct CaseLabelNode;
struct DoStatementNode;
struct WhileStatementNode;
struct ForInStatementNode;
struct ForStatementNode;
struct WithStatementNode;
struct ContinueStatementNode;
struct BreakStatementNode;
struct ReturnStatementNode;
struct ThrowStatementNode;
struct TryStatementNode;
struct CatchClauseNode;
struct FinallyClauseNode;
struct UseStatementNode;
struct IncludeStatementNode;
struct ImportDefinitionNode;
struct ImportBindingNode;
struct AnnotatedDefinitionNode;
struct AttributeListNode;
struct ExportDefinitionNode;
struct ExportBindingNode;
struct VariableDefinitionNode;
struct VariableBindingNode;
struct TypedVariableNode;
struct FunctionDefinitionNode;
struct FunctionDeclarationNode;
struct FunctionNameNode;
struct FunctionSignatureNode;
struct ParameterNode;
struct OptionalParameterNode;
struct RestParameterNode;
struct NamedParameterNode;
struct ClassDefinitionNode;
struct ClassDeclarationNode;
struct InheritanceNode;
struct NamespaceDefinitionNode;
struct PackageDefinitionNode;
struct LanguageDeclarationNode;
struct ProgramNode;
class Evaluator {
public:
bool checkFeature(Context& cx, Node* node) {
std::map<std::string,std::string>::iterator feature = cx.features.find(node->toString());
if( feature!=cx.features.end() ) {
std::string& msg = (*feature).second;
cx.err << node->toString() << ": " << msg << '\n';
return false;
} else {
return true;
}
}
// Base node
virtual Value* evaluate( Context& cx, Node* node ) {
throw;
}
// Expression evaluators
virtual Value* evaluate( Context& cx, IdentifierNode* node ) {
throw;
}
// Expression evaluators
virtual Value* evaluate( Context& cx, ThisExpressionNode* node ) {
throw;
}
virtual Value* evaluate( Context& cx, QualifiedIdentifierNode* node ) {
throw;
}
virtual Value* evaluate( Context& cx, LiteralBooleanNode* node ) {
throw;
}
virtual Value* evaluate( Context& cx, LiteralNumberNode* node ) {
throw;
}
virtual Value* evaluate( Context& cx, LiteralStringNode* node ) {
throw;
return 0;
}
virtual Value* evaluate( Context& cx, LiteralUndefinedNode* node ) {
throw;
}
virtual Value* evaluate( Context& cx, LiteralNullNode* node ) {
throw;
}
virtual Value* evaluate( Context& cx, LiteralRegExpNode* node ) {
throw;
}
virtual Value* evaluate( Context& cx, UnitExpressionNode* node ) {
throw;
}
virtual Value* evaluate( Context& cx, FunctionExpressionNode* node ) {
throw;
}
virtual Value* evaluate( Context& cx, ParenthesizedExpressionNode* node ) {
throw;
}
virtual Value* evaluate( Context& cx, ParenthesizedListExpressionNode* node ) {
throw;
}
virtual Value* evaluate( Context& cx, LiteralObjectNode* node ) {
throw;
}
virtual Value* evaluate( Context& cx, LiteralFieldNode* node ) {
throw;
}
virtual Value* evaluate( Context& cx, LiteralArrayNode* node ) {
throw;
}
virtual Value* evaluate( Context& cx, PostfixExpressionNode* node ) {
throw;
}
virtual Value* evaluate( Context& cx, NewExpressionNode* node ) {
throw;
}
virtual Value* evaluate( Context& cx, IndexedMemberExpressionNode* node ) {
throw;
}
virtual Value* evaluate( Context& cx, ClassofExpressionNode* node ) {
throw;
}
virtual Value* evaluate( Context& cx, MemberExpressionNode* node ) {
throw;
}
virtual Value* evaluate( Context& cx, CoersionExpressionNode* node ) {
throw;
}
virtual Value* evaluate( Context& cx, CallExpressionNode* node ) {
throw;
}
virtual Value* evaluate( Context& cx, GetExpressionNode* node ) {
throw;
}
virtual Value* evaluate( Context& cx, SetExpressionNode* node ) {
throw;
}
virtual Value* evaluate( Context& cx, UnaryExpressionNode* node ) {
throw;
}
virtual Value* evaluate( Context& cx, BinaryExpressionNode* node ) {
throw;
}
virtual Value* evaluate( Context& cx, ConditionalExpressionNode* node ) {
throw;
}
virtual Value* evaluate( Context& cx, AssignmentExpressionNode* node ) {
throw;
}
virtual Value* evaluate( Context& cx, ListNode* node ) {
throw;
}
// Statements
virtual Value* evaluate( Context& cx, StatementListNode* node ) {
throw;
}
virtual Value* evaluate( Context& cx, EmptyStatementNode* node ) {
throw;
}
virtual Value* evaluate( Context& cx, ExpressionStatementNode* node ) {
throw;
}
virtual Value* evaluate( Context& cx, AnnotatedBlockNode* node ) {
throw;
}
virtual Value* evaluate( Context& cx, LabeledStatementNode* node ) {
throw;
}
virtual Value* evaluate( Context& cx, IfStatementNode* node ) {
throw;
}
virtual Value* evaluate( Context& cx, SwitchStatementNode* node ) {
throw;
}
virtual Value* evaluate( Context& cx, CaseLabelNode* node ) {
throw;
}
virtual Value* evaluate( Context& cx, DoStatementNode* node ) {
throw;
}
virtual Value* evaluate( Context& cx, WhileStatementNode* node ) {
throw;
}
virtual Value* evaluate( Context& cx, ForInStatementNode* node ) {
throw;
}
virtual Value* evaluate( Context& cx, ForStatementNode* node ) {
throw;
}
virtual Value* evaluate( Context& cx, WithStatementNode* node ) {
throw;
}
virtual Value* evaluate( Context& cx, ContinueStatementNode* node ) {
throw;
}
virtual Value* evaluate( Context& cx, BreakStatementNode* node ) {
throw;
}
virtual Value* evaluate( Context& cx, ReturnStatementNode* node ) {
throw;
}
virtual Value* evaluate( Context& cx, ThrowStatementNode* node ) {
throw;
}
virtual Value* evaluate( Context& cx, TryStatementNode* node ) {
throw;
}
virtual Value* evaluate( Context& cx, CatchClauseNode* node ) {
throw;
}
virtual Value* evaluate( Context& cx, FinallyClauseNode* node ) {
throw;
}
virtual Value* evaluate( Context& cx, UseStatementNode* node ) {
throw;
}
virtual Value* evaluate( Context& cx, IncludeStatementNode* node ) {
throw;
}
// Definitions
virtual Value* evaluate( Context& cx, ImportDefinitionNode* node ) {
throw;
}
virtual Value* evaluate( Context& cx, ImportBindingNode* node ) {
throw;
}
virtual Value* evaluate( Context& cx, AnnotatedDefinitionNode* node ) {
throw;
}
virtual Value* evaluate( Context& cx, AttributeListNode* node ) {
throw;
}
virtual Value* evaluate( Context& cx, ExportDefinitionNode* node ) {
throw;
}
virtual Value* evaluate( Context& cx, ExportBindingNode* node ) {
throw;
}
virtual Value* evaluate( Context& cx, VariableDefinitionNode* node ) {
throw;
}
virtual Value* evaluate( Context& cx, VariableBindingNode* node ) {
throw;
}
virtual Value* evaluate( Context& cx, TypedVariableNode* node ) {
throw;
}
virtual Value* evaluate( Context& cx, FunctionDefinitionNode* node ) {
throw;
}
virtual Value* evaluate( Context& cx, FunctionDeclarationNode* node ) {
throw;
}
virtual Value* evaluate( Context& cx, FunctionNameNode* node ) {
throw;
}
virtual Value* evaluate( Context& cx, FunctionSignatureNode* node ) {
throw;
}
virtual Value* evaluate( Context& cx, ParameterNode* node ) {
throw;
}
virtual Value* evaluate( Context& cx, OptionalParameterNode* node ) {
throw;
}
virtual Value* evaluate( Context& cx, ClassDefinitionNode* node ) {
throw;
}
virtual Value* evaluate( Context& cx, ClassDeclarationNode* node ) {
throw;
}
virtual Value* evaluate( Context& cx, InheritanceNode* node ) {
throw;
}
virtual Value* evaluate( Context& cx, NamespaceDefinitionNode* node ) {
throw;
}
virtual Value* evaluate( Context& cx, PackageDefinitionNode* node ) {
throw;
}
virtual Value* evaluate( Context& cx, ProgramNode* node ) {
throw;
}
};
}
}
#endif // Evaluator_h
/*
* Copyright (c) 1998-2001 by Mountain View Compiler Company
* All rights reserved.
*/

View File

@@ -0,0 +1,108 @@
/**
* The base Node class.
*/
#ifndef Node_h
#define Node_h
namespace esc {
namespace v1 {
class Evaluator;
class Value;
class Context;
struct Node {
int position;
char local_var_index;
Node() {
}
Node( int position ) {
this->position = position;
}
virtual Value* evaluate( Context& cx, Evaluator* evaluator ) {
return (Value*) 0;
}
Node* first() {
return this;
}
Node* last() {
return this;
}
Node* pos(int p) {
position = p;
return this;
}
int pos() {
return position;
}
virtual const char* toString() {
return "Node";
}
virtual bool isCallExpression() {
return false;
}
virtual bool isFullNewExpression() {
return false;
}
virtual bool isFullSuperExpression() {
return false;
}
virtual bool isMemberExpression() {
return false;
}
#if 0
private static final boolean debug = false;
Block block;
Store store;
boolean isLeader;
public void markLeader() throws Exception {
if( debug ) {
Debugger.trace( "Node.markLeader() with this = " + this );
//if(this instanceof AnnotatedBlockNode) throw new Exception("blah");
}
isLeader=true;
}
public boolean isLeader() {
return isLeader;
}
public boolean isBranch() {
return false;
}
public Node[] getTargets() {
return null;
}
public String toString() {
return isLeader ? "*"+block+":" : ""+block+":";
}
#endif
};
}
}
#endif // Node_h
/*
* The end.
*/

View File

@@ -0,0 +1,47 @@
/*
* The value class from which all other values derive.
*/
#pragma warning ( disable : 4786 )
#include "NodeFactory.h"
namespace esc {
namespace v1 {
std::vector<Node*>* NodeFactory::roots;
int NodeFactory::main(int argc, char* argv[]) {
NodeFactory::init();
NodeFactory::Identifier("a");
NodeFactory::QualifiedIdentifier(
NodeFactory::Identifier("public"),
NodeFactory::Identifier("b"));
NodeFactory::LiteralNull();
NodeFactory::LiteralBoolean((bool)1);
NodeFactory::LiteralArray(
NodeFactory::List(
NULL,
NodeFactory::LiteralNumber("one")));
NodeFactory::LiteralField(
NodeFactory::Identifier("a"),
NodeFactory::LiteralBoolean((bool)1));
NodeFactory::LiteralNumber("3.1415");
NodeFactory::LiteralObject(
NodeFactory::List(
NULL,
NodeFactory::LiteralField(
NodeFactory::Identifier("a"),
NodeFactory::LiteralBoolean((bool)1))));
return 0;
}
}
}
/*
* Copyright (c) 1998-2001 by Mountain View Compiler Company
* All rights reserved.
*/

View File

@@ -0,0 +1,450 @@
/*
* Creates parse tree nodes.
*/
#ifndef NodeFactory_h
#define NodeFactory_h
#include <vector>
#include <algorithm>
#include "Node.h"
#include "Nodes.h"
namespace esc {
namespace v1 {
struct NodeFactory {
/*
* Test driver
*/
static int main(int argc, char* argv[]);
/*
* roots is a vector of references to all the nodes allocated
* since the last call to clear().
*/
static std::vector<Node*>* roots;
static void init() {
NodeFactory::roots = new std::vector<Node*>();
}
static void clear_root(Node* root) {
delete root;
}
static void clear() {
std::for_each(roots->begin(),roots->end(),clear_root);
roots->clear();
delete roots;
}
// Nodes
static IdentifierNode* Identifier( std::string name ) {
IdentifierNode* node = new IdentifierNode(name,0/*in->positionOfMark()*/);
roots->push_back(node);
return node;
}
static QualifiedIdentifierNode* QualifiedIdentifier( Node* qualifier, IdentifierNode* identifier ) {
QualifiedIdentifierNode* node = new QualifiedIdentifierNode(qualifier,identifier,identifier->pos());
roots->push_back(node);
return node;
}
static LiteralNullNode* LiteralNull() {
LiteralNullNode* node = new LiteralNullNode();
roots->push_back(node);
return node;
}
static LiteralBooleanNode* LiteralBoolean(bool value) {
LiteralBooleanNode* node = new LiteralBooleanNode(value);
roots->push_back(node);
return node;
}
static LiteralArrayNode* LiteralArray( Node* elementlist ) {
LiteralArrayNode* node = new LiteralArrayNode(elementlist);
roots->push_back(node);
return node;
}
static LiteralFieldNode* LiteralField( Node* name, Node* value ) {
LiteralFieldNode* node = new LiteralFieldNode(name,value);
roots->push_back(node);
return node;
}
static LiteralNumberNode* LiteralNumber( std::string value ) {
LiteralNumberNode* node = new LiteralNumberNode(value);
roots->push_back(node);
return node;
}
static LiteralObjectNode* LiteralObject( Node* fieldlist ) {
LiteralObjectNode* node = new LiteralObjectNode(fieldlist);
roots->push_back(node);
return node;
}
static LiteralRegExpNode* LiteralRegExp( std::string value ) {
LiteralRegExpNode* node = new LiteralRegExpNode(value);
roots->push_back(node);
return node;
}
static LiteralStringNode* LiteralString( std::string value ) {
LiteralStringNode* node = new LiteralStringNode(value);
roots->push_back(node);
return node;
}
#if 0
static LiteralTypeNode* LiteralType( Type* type ) {
LiteralTypeNode* node = new LiteralTypeNode(type);
roots->push_back(node);
return node;
}
#endif
static LiteralUndefinedNode* LiteralUndefined() {
LiteralUndefinedNode* node = new LiteralUndefinedNode();
roots->push_back(node);
return node;
}
static ParenthesizedExpressionNode* ParenthesizedExpression( Node* expr ) {
ParenthesizedExpressionNode* node = new ParenthesizedExpressionNode(expr,0/*in->positionOfMark()*/);
roots->push_back(node);
return node;
}
static ParenthesizedListExpressionNode* ParenthesizedListExpression( Node* expr ) {
ParenthesizedListExpressionNode* node = new ParenthesizedListExpressionNode(expr);
roots->push_back(node);
return node;
}
static FunctionExpressionNode* FunctionExpression( Node* name, Node* signature, Node* body ) {
FunctionExpressionNode* node = new FunctionExpressionNode(name,signature,body);
roots->push_back(node);
return node;
}
static AnnotatedDefinitionNode* AnnotatedDefinition( Node* attributes, Node* definition ) {
AnnotatedDefinitionNode* node = new AnnotatedDefinitionNode(attributes,definition);
roots->push_back(node);
return node;
}
static AttributeListNode* AttributeList( Node* item, Node* list ) {
AttributeListNode* node = new AttributeListNode(item,list);
roots->push_back(node);
return node;
}
static UnitExpressionNode* UnitExpression( Node* value, Node* type ) {
UnitExpressionNode* node = new UnitExpressionNode(value,type);
roots->push_back(node);
return node;
}
static ThisExpressionNode* ThisExpression() {
ThisExpressionNode* node = new ThisExpressionNode();
roots->push_back(node);
return node;
}
static SuperExpressionNode* SuperExpression(Node* expr) {
SuperExpressionNode* node = new SuperExpressionNode(expr);
roots->push_back(node);
return node;
}
static ListNode* List( ListNode* list, Node* item ) {
ListNode* node = new ListNode(list,item,0);
roots->push_back(node);
return node;
}
static PostfixExpressionNode* PostfixExpression( int op, Node* expr ) {
PostfixExpressionNode* node = new PostfixExpressionNode(op,expr);
roots->push_back(node);
return node;
}
static NewExpressionNode* NewExpression( Node* expr ) {
NewExpressionNode* node = new NewExpressionNode(expr);
roots->push_back(node);
return node;
}
static ClassofExpressionNode* ClassofExpression( Node* base ) {
ClassofExpressionNode* node = new ClassofExpressionNode(base);
roots->push_back(node);
return node;
}
static CallExpressionNode* CallExpression( Node* member, ListNode* args ) {
CallExpressionNode* node = new CallExpressionNode(member,args);
roots->push_back(node);
return node;
}
static GetExpressionNode* GetExpression( MemberExpressionNode* member ) {
GetExpressionNode* node = new GetExpressionNode(member);
roots->push_back(node);
return node;
}
static SetExpressionNode* SetExpression( Node* member, Node* args ) {
SetExpressionNode* node = new SetExpressionNode(member,args);
roots->push_back(node);
return node;
}
static IndexedMemberExpressionNode* IndexedMemberExpression( Node* base, Node* member ) {
IndexedMemberExpressionNode* node = new IndexedMemberExpressionNode(base,member,0/*in->positionOfMark()*/);
roots->push_back(node);
return node;
}
static MemberExpressionNode* MemberExpression( Node* base, Node* name ) {
MemberExpressionNode* node = new MemberExpressionNode(base,name,0/*in->positionOfMark()*/);
roots->push_back(node);
return node;
}
static CoersionExpressionNode* CoersionExpression( Node* expr, Node* type ) {
CoersionExpressionNode* node = new CoersionExpressionNode(expr,type,0/*in->positionOfMark()*/);
roots->push_back(node);
return node;
}
static UnaryExpressionNode* UnaryExpression( int op, Node* expr ) {
UnaryExpressionNode* node = new UnaryExpressionNode(op,expr);
roots->push_back(node);
return node;
}
static BinaryExpressionNode* BinaryExpression( int op, Node* lhs, Node* rhs ) {
BinaryExpressionNode* node = new BinaryExpressionNode(op,lhs,rhs);
roots->push_back(node);
return node;
}
static ConditionalExpressionNode* ConditionalExpression( Node* cond, Node* thenexpr, Node* elseexpr ) {
ConditionalExpressionNode* node = new ConditionalExpressionNode(cond,thenexpr,elseexpr);
roots->push_back(node);
return node;
}
static AssignmentExpressionNode* AssignmentExpression( Node* lhs, int op, Node* rhs ) {
AssignmentExpressionNode* node = new AssignmentExpressionNode(lhs,op,rhs);
roots->push_back(node);
return node;
}
static StatementListNode* StatementList( StatementListNode* list, Node* item ) {
StatementListNode* node = new StatementListNode(list,item);
roots->push_back(node);
return node;
}
static EmptyStatementNode* EmptyStatement() {
EmptyStatementNode* node = new EmptyStatementNode();
roots->push_back(node);
return node;
}
static ExpressionStatementNode* ExpressionStatement( Node* expr ) {
ExpressionStatementNode* node = new ExpressionStatementNode(expr);
roots->push_back(node);
return node;
}
static AnnotatedBlockNode* AnnotatedBlock( Node* attributes, Node* definition ) {
AnnotatedBlockNode* node = new AnnotatedBlockNode(attributes,definition);
roots->push_back(node);
return node;
}
static LabeledStatementNode* LabeledStatement( Node* label, Node* statement ) {
LabeledStatementNode* node = new LabeledStatementNode(label,statement);
roots->push_back(node);
return node;
}
static IfStatementNode* IfStatement( Node* test, Node* tblock, Node* eblock ) {
IfStatementNode* node = new IfStatementNode(test,tblock,eblock);
roots->push_back(node);
return node;
}
static SwitchStatementNode* SwitchStatement( Node* expr, StatementListNode* statements ) {
SwitchStatementNode* node = new SwitchStatementNode(expr,statements);
roots->push_back(node);
return node;
}
static CaseLabelNode* CaseLabel( Node* label ) {
CaseLabelNode* node = new CaseLabelNode(label);
roots->push_back(node);
return node;
}
static DoStatementNode* DoStatement( Node* block, Node* expr ) {
DoStatementNode* node = new DoStatementNode(block,expr);
roots->push_back(node);
return node;
}
static WhileStatementNode* WhileStatement( Node* expr, Node* statement ) {
WhileStatementNode* node = new WhileStatementNode(expr,statement);
roots->push_back(node);
return node;
}
static ForInStatementNode* ForInStatement( Node* expr1, Node* expr2, Node* statement ) {
ForInStatementNode* node = new ForInStatementNode(expr1,expr2,statement);
roots->push_back(node);
return node;
}
static ForStatementNode* ForStatement( Node* expr1, Node* expr2, Node* expr3, Node* statement ) {
ForStatementNode* node = new ForStatementNode(expr1,expr2,expr3,statement);
roots->push_back(node);
return node;
}
static WithStatementNode* WithStatement( Node* expr, Node* statement ) {
WithStatementNode* node = new WithStatementNode(expr,statement);
roots->push_back(node);
return node;
}
static ContinueStatementNode* ContinueStatement(Node* expr) {
ContinueStatementNode* node = new ContinueStatementNode(expr);
roots->push_back(node);
return node;
}
static BreakStatementNode* BreakStatement(Node* expr) {
BreakStatementNode* node = new BreakStatementNode(expr);
roots->push_back(node);
return node;
}
static ReturnStatementNode* ReturnStatement( Node* expr ) {
ReturnStatementNode* node = new ReturnStatementNode(expr);
roots->push_back(node);
return node;
}
static ThrowStatementNode* ThrowStatement(Node* list) {
ThrowStatementNode* node = new ThrowStatementNode(list);
roots->push_back(node);
return node;
}
static TryStatementNode* TryStatement(Node* tryblock, StatementListNode* catchlist, Node* finallyblock) {
TryStatementNode* node = new TryStatementNode(tryblock,catchlist,finallyblock);
roots->push_back(node);
return node;
}
static CatchClauseNode* CatchClause(Node* parameter, Node* block) {
CatchClauseNode* node = new CatchClauseNode(parameter,block);
roots->push_back(node);
return node;
}
static FinallyClauseNode* FinallyClause( Node* block ) {
FinallyClauseNode* node = new FinallyClauseNode(block);
roots->push_back(node);
return node;
}
static IncludeStatementNode* IncludeStatement( Node* list ) {
IncludeStatementNode* node = new IncludeStatementNode(list);
roots->push_back(node);
return node;
}
static UseStatementNode* UseStatement( Node* expr ) {
UseStatementNode* node = new UseStatementNode(expr);
roots->push_back(node);
return node;
}
static ImportDefinitionNode* ImportDefinition( Node* item, Node* list ) {
ImportDefinitionNode* node = new ImportDefinitionNode(item,list);
roots->push_back(node);
return node;
}
static ImportBindingNode* ImportBinding( Node* identifer, Node* item ) {
ImportBindingNode* node = new ImportBindingNode(identifer,item);
roots->push_back(node);
return node;
}
static ExportDefinitionNode* ExportDefinition( Node* list ) {
ExportDefinitionNode* node = new ExportDefinitionNode(list);
roots->push_back(node);
return node;
}
static ExportBindingNode* ExportBinding( Node* name, Node* value ) {
ExportBindingNode* node = new ExportBindingNode(name,value);
roots->push_back(node);
return node;
}
static VariableDefinitionNode* VariableDefinition( int kind, Node* list ) {
VariableDefinitionNode* node = new VariableDefinitionNode(kind,list,list->pos());
roots->push_back(node);
return node;
}
static VariableBindingNode* VariableBinding( Node* identifier, Node* initializer ) {
VariableBindingNode* node = new VariableBindingNode(identifier,initializer);
roots->push_back(node);
return node;
}
static TypedVariableNode* TypedVariable( Node* identifier, Node* type ) {
TypedVariableNode* node = new TypedVariableNode(identifier,type,type!=NULL?type->pos():identifier->pos());
roots->push_back(node);
return node;
}
static FunctionDefinitionNode* FunctionDefinition( Node* decl, Node* body ) {
FunctionDefinitionNode* node = new FunctionDefinitionNode(decl,body);
roots->push_back(node);
return node;
}
static FunctionDeclarationNode* FunctionDeclaration( Node* name, Node* signature ) {
FunctionDeclarationNode* node = new FunctionDeclarationNode(name,signature);
roots->push_back(node);
return node;
}
static FunctionSignatureNode* FunctionSignature( Node* parameter, Node* result ) {
FunctionSignatureNode* node = new FunctionSignatureNode(parameter,result);
roots->push_back(node);
return node;
}
static FunctionNameNode* FunctionName( int kind, Node* name ) {
FunctionNameNode* node = new FunctionNameNode(kind,name);
roots->push_back(node);
return node;
}
static RestParameterNode* RestParameter( Node* expr ) {
RestParameterNode* node = new RestParameterNode(expr);
roots->push_back(node);
return node;
}
static ParameterNode* Parameter( Node* identifer, Node* type ) {
ParameterNode* node = new ParameterNode(identifer,type);
roots->push_back(node);
return node;
}
static OptionalParameterNode* OptionalParameter( Node* identifer, Node* init ) {
OptionalParameterNode* node = new OptionalParameterNode(identifer,init);
roots->push_back(node);
return node;
}
static NamedParameterNode* NamedParameter( Node* name, Node* parameter ) {
NamedParameterNode* node = new NamedParameterNode(name,parameter);
roots->push_back(node);
return node;
}
static ClassDeclarationNode* ClassDeclaration( Node* name ) {
ClassDeclarationNode* node = new ClassDeclarationNode(name);
roots->push_back(node);
return node;
}
static ClassDefinitionNode* ClassDefinition( Node* name, Node* interfaces, Node* statements ) {
ClassDefinitionNode* node = new ClassDefinitionNode(name,interfaces,statements);
roots->push_back(node);
return node;
}
static InheritanceNode* Inheritance( Node* baseclass, Node* interfaces ) {
InheritanceNode* node = new InheritanceNode(baseclass,interfaces);
roots->push_back(node);
return node;
}
static NamespaceDefinitionNode* NamespaceDefinition( Node* identifier, Node* list ) {
NamespaceDefinitionNode* node = new NamespaceDefinitionNode(identifier,list);
roots->push_back(node);
return node;
}
static LanguageDeclarationNode* LanguageDeclaration( Node* list ) {
LanguageDeclarationNode* node = new LanguageDeclarationNode(list);
roots->push_back(node);
return node;
}
static PackageDefinitionNode* PackageDefinition( Node* name, Node* block ) {
PackageDefinitionNode* node = new PackageDefinitionNode(name,block);
roots->push_back(node);
return node;
}
static ProgramNode* Program( Node* statements ) {
ProgramNode* node = new ProgramNode(statements);
roots->push_back(node);
return node;
}
};
}
}
#endif // NodeFactory_h
/*
* Copyright (c) 1998-2001 by Mountain View Compiler Company
* All rights reserved.
*/

View File

@@ -0,0 +1,746 @@
/**
* The base visitor object extended by semantic evaluators.
*
* This is a visitor that is used by the compiler for various forms for
* evaluation of a parse tree (e.g. a type evaluator might compute the
* static type of an expression.)
*/
#ifndef NodePrinter_h
#define NodePrinter_h
#pragma warning ( disable : 4786 )
#include "Value.h"
#include "Context.h"
#include <string>
#include <sstream>
namespace esc {
namespace v1 {
struct Node;
struct IdentifierNode;
struct ThisExpressionNode;
struct SuperExpressionNode;
struct QualifiedIdentifierNode;
struct LiteralNullNode;
struct LiteralBooleanNode;
struct LiteralNumberNode;
struct LiteralStringNode;
struct LiteralUndefinedNode;
struct LiteralRegExpNode;
struct UnitExpressionNode;
struct FunctionExpressionNode;
struct ParenthesizedExpressionNode;
struct ParenthesizedListExpressionNode;
struct LiteralObjectNode;
struct LiteralFieldNode;
struct LiteralArrayNode;
struct PostfixExpressionNode;
struct NewExpressionNode;
struct IndexedMemberExpressionNode;
struct ClassofExpressionNode;
struct MemberExpressionNode;
struct CoersionExpressionNode;
struct CallExpressionNode;
struct GetExpressionNode;
struct SetExpressionNode;
struct UnaryExpressionNode;
struct BinaryExpressionNode;
struct ConditionalExpressionNode;
struct AssignmentExpressionNode;
struct ListNode;
struct StatementListNode;
struct EmptyStatementNode;
struct ExpressionStatementNode;
struct AnnotatedBlockNode;
struct LabeledStatementNode;
struct IfStatementNode;
struct SwitchStatementNode;
struct CaseLabelNode;
struct DoStatementNode;
struct WhileStatementNode;
struct ForInStatementNode;
struct ForStatementNode;
struct WithStatementNode;
struct ContinueStatementNode;
struct BreakStatementNode;
struct ReturnStatementNode;
struct ThrowStatementNode;
struct TryStatementNode;
struct CatchClauseNode;
struct FinallyClauseNode;
struct UseStatementNode;
struct IncludeStatementNode;
struct ImportDefinitionNode;
struct ImportBindingNode;
struct AnnotatedDefinitionNode;
struct AttributeListNode;
struct ExportDefinitionNode;
struct ExportBindingNode;
struct VariableDefinitionNode;
struct VariableBindingNode;
struct TypedVariableNode;
struct FunctionDefinitionNode;
struct FunctionDeclarationNode;
struct FunctionNameNode;
struct FunctionSignatureNode;
struct ParameterNode;
struct OptionalParameterNode;
struct RestParameterNode;
struct NamedParameterNode;
struct ClassDefinitionNode;
struct ClassDeclarationNode;
struct InheritanceNode;
struct NamespaceDefinitionNode;
struct PackageDefinitionNode;
struct LanguageDeclarationNode;
struct ProgramNode;
class NodePrinter : public Evaluator {
std::ostringstream out;
int level;
int mode;
void separate() {
if( mode == machine_mode ) {
out << "|";
}
}
void push_in() {
++level;
if( mode == machine_mode ) {
out << "[";
} else {
out << " ";
}
}
void pop_out() {
if( mode == machine_mode ) {
out << "]";
}
--level;
}
void indent() {
if( mode == man_mode ) {
out << '\n';
for( int i = level; i; --i ) {
out << " ";
}
}
}
public:
std::string str() {
return out.str();
}
enum {
man_mode,
machine_mode,
};
NodePrinter(int mode = man_mode) : level(0), mode(mode) {
}
// Base node
virtual Value* evaluate( Context& cx, Node* node ) {
indent();
out << "error:undefined printer method";
return 0;
}
// Expression evaluators
virtual Value* evaluate( Context& cx, IdentifierNode* node ) {
indent();
out << "Identifier";
push_in();
out << node->name;
pop_out();
return 0;
}
// Expression evaluators
virtual Value* evaluate( Context& cx, ThisExpressionNode* node ) {
indent();
out << "ThisExpression";
return 0;
}
virtual Value* evaluate( Context& cx, QualifiedIdentifierNode* node ) {
indent();
out << "QualifiedIdentifier";
push_in();
out << node->name;
separate();
if( node->qualifier ) {
node->qualifier->evaluate(cx,this);
}
pop_out();
return 0;
}
virtual Value* evaluate( Context& cx, LiteralBooleanNode* node ) {
indent();
out << "LiteralBoolean:";
out << node->value;
return 0;
}
virtual Value* evaluate( Context& cx, LiteralNumberNode* node ) {
indent();
out << "LiteralNumber:";
out << node->value.c_str();
return 0;
}
virtual Value* evaluate( Context& cx, LiteralStringNode* node ) {
indent();
out << "LiteralString:";
out << node->value.c_str();
return 0;
}
virtual Value* evaluate( Context& cx, LiteralUndefinedNode* node ) {
indent();
out << "LiteralUndefined";
return 0;
}
virtual Value* evaluate( Context& cx, LiteralNullNode* node ) {
indent();
out << "LiteralNull";
return 0;
}
virtual Value* evaluate( Context& cx, LiteralRegExpNode* node ) {
indent();
out << "LiteralRegExp";
return 0;
}
virtual Value* evaluate( Context& cx, UnitExpressionNode* node ) {
indent();
out << "UnitExpression";
push_in();
if( node->value ) {
node->value->evaluate(cx,this);
}
separate();
if( node->type ) {
node->type->evaluate(cx,this);
}
pop_out();
return 0;
}
virtual Value* evaluate( Context& cx, FunctionExpressionNode* node ) {
indent();
out << "FunctionExpression";
push_in();
if( node->name ) {
node->name->evaluate(cx,this);
}
separate();
if( node->signature ) {
node->signature->evaluate(cx,this);
}
separate();
if( node->body ) {
node->body->evaluate(cx,this);
}
pop_out();
return 0;
}
virtual Value* evaluate( Context& cx, ParenthesizedExpressionNode* node ) {
indent();
out << "ParenthesizedExpression";
return 0;
}
virtual Value* evaluate( Context& cx, ParenthesizedListExpressionNode* node ) {
indent();
out << "ParenthesizedListExpression";
if( node->expr ) {
node->expr->evaluate(cx,this);
}
return 0;
}
virtual Value* evaluate( Context& cx, LiteralObjectNode* node ) {
indent();
out << "LiteralObject";
return 0;
}
virtual Value* evaluate( Context& cx, LiteralFieldNode* node ) {
indent();
out << "LiteralField";
return 0;
}
virtual Value* evaluate( Context& cx, LiteralArrayNode* node ) {
indent();
out << "LiteralArray";
push_in();
if( node->elementlist ) {
node->elementlist->evaluate(cx,this);
}
pop_out();
return 0;
}
virtual Value* evaluate( Context& cx, PostfixExpressionNode* node ) {
indent();
out << "PostfixExpression";
push_in();
out << Token::getTokenClassName(node->op);
pop_out();
separate();
push_in();
if( node->expr ) {
node->expr->evaluate(cx,this);
}
pop_out();
return 0;
}
virtual Value* evaluate( Context& cx, NewExpressionNode* node ) {
indent();
out << "NewExpression";
push_in();
if( node->expr ) {
node->expr->evaluate(cx,this);
}
pop_out();
return 0;
}
virtual Value* evaluate( Context& cx, IndexedMemberExpressionNode* node ) {
indent();
out << "IndexedMemberExpression";
push_in();
if( node->base ) {
node->base->evaluate(cx,this);
}
separate();
if( node->expr ) {
node->expr->evaluate(cx,this);
}
pop_out();
return 0;
}
virtual Value* evaluate( Context& cx, ClassofExpressionNode* node ) {
indent();
out << "ClassofExpression";
push_in();
if( node->base ) {
node->base->evaluate(cx,this);
}
pop_out();
return 0;
}
virtual Value* evaluate( Context& cx, MemberExpressionNode* node ) {
indent();
out << "MemberExpression";
push_in();
if( node->base ) {
node->base->evaluate(cx,this);
}
separate();
if( node->expr ) {
node->expr->evaluate(cx,this);
}
pop_out();
return 0;
}
virtual Value* evaluate( Context& cx, CoersionExpressionNode* node ) {
indent();
out << "CoersionExpression";
push_in();
if( node->expr ) {
node->expr->evaluate(cx,this);
}
separate();
if( node->type ) {
node->type->evaluate(cx,this);
}
pop_out();
return 0;
}
virtual Value* evaluate( Context& cx, CallExpressionNode* node ) {
indent();
out << "CallExpression";
push_in();
if( node->member ) {
node->member->evaluate(cx,this);
}
separate();
if( node->args ) {
node->args->evaluate(cx,this);
}
pop_out();
return 0;
}
virtual Value* evaluate( Context& cx, GetExpressionNode* node ) {
indent();
out << "GetExpression";
push_in();
if( node->member ) {
node->member->evaluate(cx,this);
}
pop_out();
return 0;
}
virtual Value* evaluate( Context& cx, SetExpressionNode* node ) {
indent();
out << "SetExpression";
return 0;
}
virtual Value* evaluate( Context& cx, UnaryExpressionNode* node ) {
indent();
out << "UnaryExpression";
push_in();
out << Token::getTokenClassName(node->op);
pop_out();
separate();
push_in();
if( node->expr ) {
node->expr->evaluate(cx,this);
}
pop_out();
return 0;
}
virtual Value* evaluate( Context& cx, BinaryExpressionNode* node ) {
indent();
out << "BinaryExpression";
push_in();
out << Token::getTokenClassName(node->op);
pop_out();
separate();
push_in();
if( node->lhs ) {
node->lhs->evaluate(cx,this);
}
separate();
if( node->rhs ) {
node->rhs->evaluate(cx,this);
}
pop_out();
return 0;
}
virtual Value* evaluate( Context& cx, ConditionalExpressionNode* node ) {
indent();
out << "ConditionalExpression";
push_in();
if( node->condition ) {
node->condition->evaluate(cx,this);
}
pop_out();
separate();
push_in();
if( node->thenexpr ) {
node->thenexpr->evaluate(cx,this);
}
separate();
if( node->elseexpr ) {
node->elseexpr->evaluate(cx,this);
}
pop_out();
return 0;
}
virtual Value* evaluate( Context& cx, AssignmentExpressionNode* node ) {
indent();
out << "AssignmentExpression";
push_in();
out << Token::getTokenClassName(node->op);
pop_out();
separate();
push_in();
if( node->lhs ) {
node->lhs->evaluate(cx,this);
}
separate();
if( node->rhs ) {
node->rhs->evaluate(cx,this);
}
pop_out();
return 0;
}
virtual Value* evaluate( Context& cx, ListNode* node ) {
indent();
out << "List";
push_in();
if( node->list ) {
node->list->evaluate(cx,this);
}
separate();
if( node->item ) {
node->item->evaluate(cx,this);
}
pop_out();
return 0;
}
// Statements
virtual Value* evaluate( Context& cx, StatementListNode* node ) {
indent();
out << "StatementList";
push_in();
if( node->list ) {
node->list->evaluate(cx,this);
}
if( node->item ) {
node->item->evaluate(cx,this);
}
pop_out();
return 0;
}
virtual Value* evaluate( Context& cx, EmptyStatementNode* node ) {
indent();
out << "EmptyStatement";
return 0;
}
virtual Value* evaluate( Context& cx, ExpressionStatementNode* node ) {
indent();
out << "ExpressionStatement";
push_in();
if( node->expr ) {
node->expr->evaluate(cx,this);
}
pop_out();
return 0;
}
virtual Value* evaluate( Context& cx, AnnotatedBlockNode* node ) {
indent();
out << "AnnotatedBlock";
return 0;
}
virtual Value* evaluate( Context& cx, LabeledStatementNode* node ) {
indent();
out << "LabeledStatement";
return 0;
}
virtual Value* evaluate( Context& cx, IfStatementNode* node ) {
indent();
out << "IfStatement";
return 0;
}
virtual Value* evaluate( Context& cx, SwitchStatementNode* node ) {
indent();
out << "SwitchStatement";
return 0;
}
virtual Value* evaluate( Context& cx, CaseLabelNode* node ) {
indent();
out << "CaseLabel";
return 0;
}
virtual Value* evaluate( Context& cx, DoStatementNode* node ) {
indent();
out << "DoStatement";
return 0;
}
virtual Value* evaluate( Context& cx, WhileStatementNode* node ) {
indent();
out << "WhileStatement";
return 0;
}
virtual Value* evaluate( Context& cx, ForInStatementNode* node ) {
indent();
out << "ForInStatement";
return 0;
}
virtual Value* evaluate( Context& cx, ForStatementNode* node ) {
indent();
out << "ForStatement";
return 0;
}
virtual Value* evaluate( Context& cx, WithStatementNode* node ) {
indent();
out << "WithStatement";
return 0;
}
virtual Value* evaluate( Context& cx, ContinueStatementNode* node ) {
indent();
out << "ContinueStatement";
return 0;
}
virtual Value* evaluate( Context& cx, BreakStatementNode* node ) {
indent();
out << "BreakStatement";
return 0;
}
virtual Value* evaluate( Context& cx, ReturnStatementNode* node ) {
indent();
out << "ReturnStatement";
return 0;
}
virtual Value* evaluate( Context& cx, ThrowStatementNode* node ) {
indent();
out << "ThrowStatement";
return 0;
}
virtual Value* evaluate( Context& cx, TryStatementNode* node ) {
indent();
out << "TryStatement";
return 0;
}
virtual Value* evaluate( Context& cx, CatchClauseNode* node ) {
indent();
out << "CatchClause";
return 0;
}
virtual Value* evaluate( Context& cx, FinallyClauseNode* node ) {
indent();
out << "FinallyClause";
return 0;
}
virtual Value* evaluate( Context& cx, UseStatementNode* node ) {
indent();
out << "UseStatement";
return 0;
}
virtual Value* evaluate( Context& cx, IncludeStatementNode* node ) {
indent();
out << "IncludeStatement";
return 0;
}
// Definitions
virtual Value* evaluate( Context& cx, ImportDefinitionNode* node ) {
indent();
out << "ImportDefinition";
return 0;
}
virtual Value* evaluate( Context& cx, ImportBindingNode* node ) {
indent();
out << "ImportBinding";
return 0;
}
virtual Value* evaluate( Context& cx, AnnotatedDefinitionNode* node ) {
indent();
out << "AnnotatedDefinition";
return 0;
}
virtual Value* evaluate( Context& cx, AttributeListNode* node ) {
indent();
out << "AttributeList";
return 0;
}
virtual Value* evaluate( Context& cx, ExportDefinitionNode* node ) {
indent();
out << "ExportDefinition";
return 0;
}
virtual Value* evaluate( Context& cx, ExportBindingNode* node ) {
indent();
out << "ExportBinding";
return 0;
}
virtual Value* evaluate( Context& cx, VariableDefinitionNode* node ) {
indent();
out << "VariableDefinition";
return 0;
}
virtual Value* evaluate( Context& cx, VariableBindingNode* node ) {
indent();
out << "VariableBinding";
return 0;
}
virtual Value* evaluate( Context& cx, TypedVariableNode* node ) {
indent();
out << "TypedVariable";
return 0;
}
virtual Value* evaluate( Context& cx, FunctionDefinitionNode* node ) {
indent();
out << "FunctionDefinition";
return 0;
}
virtual Value* evaluate( Context& cx, FunctionDeclarationNode* node ) {
indent();
out << "FunctionDeclaration";
return 0;
}
virtual Value* evaluate( Context& cx, FunctionNameNode* node ) {
indent();
out << "FunctionName";
return 0;
}
virtual Value* evaluate( Context& cx, FunctionSignatureNode* node ) {
indent();
out << "FunctionSignature";
push_in();
if( node->parameter ) {
node->parameter->evaluate(cx,this);
}
separate();
if( node->result ) {
node->result->evaluate(cx,this);
}
pop_out();
return 0;
}
virtual Value* evaluate( Context& cx, ParameterNode* node ) {
indent();
out << "Parameter";
push_in();
if( node->identifier ) {
node->identifier->evaluate(cx,this);
}
separate();
if( node->type ) {
node->type->evaluate(cx,this);
}
pop_out();
return 0;
}
virtual Value* evaluate( Context& cx, OptionalParameterNode* node ) {
indent();
out << "OptionalParameter";
return 0;
}
virtual Value* evaluate( Context& cx, ClassDefinitionNode* node ) {
indent();
out << "ClassDefinition";
return 0;
}
virtual Value* evaluate( Context& cx, ClassDeclarationNode* node ) {
indent();
out << "ClassDeclaration";
return 0;
}
virtual Value* evaluate( Context& cx, InheritanceNode* node ) {
indent();
out << "Inheritance";
return 0;
}
virtual Value* evaluate( Context& cx, NamespaceDefinitionNode* node ) {
indent();
out << "NamespaceDefinition";
return 0;
}
virtual Value* evaluate( Context& cx, PackageDefinitionNode* node ) {
indent();
out << "PackageDefinition: ";
return 0;
}
virtual Value* evaluate( Context& cx, ProgramNode* node ) {
indent();
out << "Program";
push_in();
if( node->statements ) {
node->statements->evaluate(cx,this);
}
pop_out();
out << '\n';
return 0;
}
};
}
}
#endif // NodePrinter_h
/*
* Copyright (c) 1998-2001 by Mountain View Compiler Company
* All rights reserved.
*/

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,427 @@
/*
* The value class from which all other values derive.
*/
#pragma warning ( disable : 4786 )
#include <string>
#include <map>
#include <algorithm>
#include "Context.h"
#include "Scope.h"
#include "Value.h"
#include "Type.h"
#include "Slot.h"
#include "ObjectValue.h"
#include "ReferenceValue.h"
#include "TypeValue.h"
namespace esc {
namespace v1 {
ObjectValue* ObjectValue::undefinedValue;
ObjectValue* ObjectValue::nullValue;
ObjectValue* ObjectValue::trueValue;
ObjectValue* ObjectValue::falseValue;
ObjectValue* ObjectValue::publicNamespace;
ObjectValue* ObjectValue::objectPrototype;
Slot default_slot;
void ObjectValue::init() {
ObjectValue::undefinedValue = new ObjectValue();
ObjectValue::nullValue = new ObjectValue();
ObjectValue::trueValue = new ObjectValue();
ObjectValue::falseValue = new ObjectValue();
ObjectValue::publicNamespace = new ObjectValue(TypeValue::namespaceType);
ObjectValue::objectPrototype = new ObjectValue();
}
void ObjectValue::fini() {
}
ObjectValue::ObjectValue()
: names(*new std::map<std::string,Qualifiers>()),
slots(*new std::vector<Slot>(3,default_slot)),
dyna_slots(*new std::vector<Slot>),
frozen_flag(false),
first_index(0) {
initInstance(0,0);
}
ObjectValue::ObjectValue(Builder& builder)
: names(*new std::map<std::string,Qualifiers>()),
slots(*new std::vector<Slot>(3,default_slot)),
dyna_slots(*new std::vector<Slot>),
frozen_flag(false),
first_index(0) {
initInstance(0,TypeValue::objectType);
Context cx;
builder.build(cx,this);
}
ObjectValue::ObjectValue(bool value)
: names(*new std::map<std::string,Qualifiers>()),
slots(*new std::vector<Slot>(3,default_slot)),
dyna_slots(*new std::vector<Slot>),
frozen_flag(false),
first_index(0) {
initInstance(TypeValue::booleanType->prototype,TypeValue::booleanType);
Context& cx = *new Context();
Slot* slot = getSlot(cx,first_index+SLOT_VALUE);
slot->intValue = value;
slot->type = TypeValue::booleanType;
slot->attrs = 0;
}
// Construct an object with a given prototype object.
ObjectValue::ObjectValue(ObjectValue* protoObject)
: names(*new std::map<std::string,Qualifiers>()),
slots(*new std::vector<Slot>(3,default_slot)),
dyna_slots(*new std::vector<Slot>),
frozen_flag(false),
first_index(protoObject->getLastSlotIndex()) {
initInstance(protoObject,TypeValue::objectType);
}
// Construct an object with a class defined.
ObjectValue::ObjectValue(TypeValue* classObject)
: names(*new std::map<std::string,Qualifiers>()),
slots(*new std::vector<Slot>(3,default_slot)),
dyna_slots(*new std::vector<Slot>),
frozen_flag(false),
first_index(classObject->prototype->getLastSlotIndex()) {
initInstance(classObject->prototype,classObject);
}
void ObjectValue::initInstance(ObjectValue* protoObject,TypeValue* classObject) {
Context& cx = *new Context();
Slot* slot;
slot = getSlot(cx,first_index+SLOT_PROTO);
slot->value = protoObject;
slot->type = TypeValue::objectType;
slot->attrs = 0;
slot = getSlot(cx,first_index+SLOT_CLASS);
slot->value = classObject;
slot->type = TypeValue::typeType;
slot->attrs = 0;
// Call the class object's builder method to initialize
// this instance.
if( classObject ) {
classObject->build(cx,this);
}
}
/*
* Scope methods
*/
/*
* Look for a property name in the object.
*/
bool ObjectValue::hasName(Context& cx, std::string name, Value* qualifier) {
Names::iterator nameit = names.find(name);
if( nameit == names.end() ) {
return (bool)0;
}
Qualifiers& qual = (*nameit).second;
return qual.find(qualifier) != qual.end();
}
Namespaces* ObjectValue::hasNames(Context& cx, std::string name, Namespaces* namespaces) {
Namespaces* hasNamespaces = new Namespaces();
Names::iterator nameit = names.find(name);
if( nameit == names.end() ) {
return (Namespaces*)0;
}
Qualifiers* quals = &(*nameit).second;
// For each member of namespaces, see if there
// is a matching qualifier.
for(int i = 0; i < namespaces->size(); i++ ) {
Value* qual = namespaces->at(i);
if( quals->find(qual) != quals->end() ) {
hasNamespaces->push_back(qual);
}
}
return hasNamespaces;
}
/*
* Get the slot for a property.
*
* WARNING:
* Before calling this method you must call hasName to ensure that
* the requested property exists.
*/
Slot* ObjectValue::get(Context& cx, std::string name, Value* qualifier) {
std::map<Value*,int>& prop = names[name];
int index = prop[qualifier];
return getSlot(cx,index);
}
/*
* Set the value of a property.
*/
int ObjectValue::define(Context& cx, std::string name, Value* qualifier, int index) {
// Get the property for name
std::map<std::string,Qualifiers>::iterator nameit = names.find(name);
// If there is one, then get the qualifier map for that name.
// Otherwise, create a qualifier map and a new property.
if( nameit == names.end() ) {
Qualifiers qualifiers;
names[name] = qualifiers;
}
// Add the qualifier to the qualifiers map, and set its value to index.
std::map<Value*,int>& prop = names[name];
prop[qualifier] = index;
return index;
}
/*
* Add a slot to this object. This object's fixed slots
* (that is, all slots added before freezeSlots is called)
* begin where the [[Prototype]] indexes end.
*
* If [[Prototype]] object has not been frozen or this
* object has been frozen, then addSlot allocates the
* slot in the dynamic slot space.
*/
int ObjectValue::addSlot(Context& cx) {
Slot slot;
int index;
if( proto(cx) && proto(cx)->isFixed() && !this->isFixed() ) {
index = first_index + slots.size();
slots.push_back(slot);
} else if( !this->isFixed() ) {
index = slots.size();
slots.push_back(slot);
} else {
index = -dyna_slots.size();
dyna_slots.push_back(slot);
}
return index;
}
/*
* Get the slot for an index. If it is a fixed slot
* it will have a positive value. dynamic slots have
* negative values.
*/
Slot* ObjectValue::getSlot(Context& cx, int index) {
Slot* slot;
if( ((unsigned)index) < first_index ) {
slot = proto(cx)->getSlot(cx,index);
} else if (index < 0) {
slot = &dyna_slots[-index];
} else {
slot = &slots[index-first_index];
}
return slot;
}
/*
* Get the slot index of a named property.
*
* Before calling this method you must call hasName to ensure that
* the requested property exists.
*/
int ObjectValue::getSlotIndex(Context& cx, std::string name, Value* qualifier) {
std::map<Value*,int>& prop = names[name];
int size = prop.size();
int index = prop[qualifier];
return index;
}
bool ObjectValue::isFixed() {
return frozen_flag;
}
int ObjectValue::getFirstSlotIndex() {
return first_index;
}
int ObjectValue::getLastSlotIndex() {
frozen_flag = true;
return first_index+slots.size()-1;
}
ObjectValue* ObjectValue::proto(Context& cx) {
return this->getSlot(cx,first_index+SLOT_PROTO)->objValue;
}
TypeValue* ObjectValue::getType(Context& cx) {
return reinterpret_cast<TypeValue*>(this->getSlot(cx,first_index+SLOT_CLASS)->objValue);
}
/*
* Test driver
*/
int ObjectValue::main(int argc, char* argv[]) {
Context& cx = *new Context();
ObjectValue ob;
ObjectValue q1,q2,q3;
int i1,i2,i3;
i1 = ob.addSlot(cx); // add a slot
i1 = ob.define(cx,"a",&q1,i1); // define a property
i2 = ob.addSlot(cx);
i2 = ob.define(cx,"a",&q2,i2);
i3 = ob.addSlot(cx);
i3 = ob.define(cx,"a",&q3,i2);
//ObjectValue v1,v2,v3;
ob.get(cx,"a",&q1)->intValue = 10;
ob.get(cx,"a",&q2)->intValue = 20;
int v3 = ob.get(cx,"a",&q3)->intValue;
Slot* s1 = ob.getSlot(cx,i1);
Slot* s2 = ob.getSlot(cx,i2);
Slot* s3 = ob.getSlot(cx,i3);
ObjectValue b((bool)1);
delete &cx;
testClass(argc,argv);
return 0;
}
// Test the case:
// class B { static var xg = 1; var xp = 2; }
// var b = new B;
// b.xi = 3;
// b.class.xg;
// b.xp;
// b.xi;
int ObjectValue::testClass(int argc, char* argv[]) {
Context cx;;
// Allocate the parts
ObjectValue global;
ObjectValue default_ns;
// Wire them together
int slot_index;
Slot* slot;
// Init the proto object
ObjectValue b_proto;
slot_index = b_proto.addSlot(cx); // add a slot
slot_index = b_proto.define(cx,"xp",&default_ns,slot_index); // define a property
slot = b_proto.getSlot(cx,slot_index);
slot->intValue = 10;
// Init the class object
TypeValue b_class;
slot_index = b_class.addSlot(cx); // add a slot
slot_index = b_class.define(cx,"xg",&default_ns,slot_index); // define a property
slot = b_class.getSlot(cx,slot_index);
slot->intValue = 30;
// Init the instance object
ObjectValue b_instance(b_proto);
int first_index = b_instance.getFirstSlotIndex();
slot = b_instance.getSlot(cx,first_index+SLOT_PROTO);
slot->value = &b_proto;
slot->type = TypeValue::objectType;
slot->attrs = 0;
slot_index = b_instance.define(cx,"class",&default_ns,first_index+SLOT_CLASS); // define a property
slot = b_instance.getSlot(cx,first_index+SLOT_CLASS);
slot->value = &b_class;
slot->type = TypeValue::typeType;
slot->attrs = 0;
slot_index = b_instance.addSlot(cx); // add a slot
slot_index = b_instance.define(cx,"xi",&default_ns,slot_index); // define a property
slot = b_instance.getSlot(cx,slot_index);
slot->intValue = 20;
slot_index = global.addSlot(cx); // add a slot
slot_index = global.define(cx,"b",&default_ns,slot_index); // define a property
slot = global.getSlot(cx,slot_index);
slot->objValue = &b_instance;
// Make and evaluate some references
// b.xp
ReferenceValue r1(&b_instance,"xp",&default_ns);
Slot* sp;
sp = r1.getSlot(cx);
int sp_index = r1.getSlotIndex();
sp = b_instance.getSlot(cx,sp_index);
// b.xi
ReferenceValue r2(&b_instance,"xi",&default_ns);
Slot* si = r2.getSlot(cx);
// b.class.xg
ReferenceValue r3(&b_instance,"class",&default_ns);
ObjectValue& vB = *((ObjectValue*)r3.getValue(cx));
ReferenceValue r4(&vB,"xg",&default_ns);
Slot* sg = r4.getSlot(cx);
return 0;
}
}
}
/*
* Written by Jeff Dyer
* Copyright (c) 1998-2001 by Mountain View Compiler Company
* All rights reserved.
*/

View File

@@ -0,0 +1,175 @@
/*
* This class is the building block for all ECMA values. Object values
* are a sequence of instances linked through the [[Prototype]] slot.
* Classes are a sequence of instances of the sub-class TypeValue, also
* linked through the [[Prototype]] slot. Lookup of class and instance
* properties uses the same algorithm to find a name. Names are bound
* to slots. Slots contain values that are methods for accessing or
* computing program values (i.e running code.)
*
* An object consists of a table of names, and a vector of slots. The
* slots hold methods for accessing and computing values. An object
* also has a private data accessible to the methods and accessors of
* the object.
*
* All symbolic references to the properties of an object are bound
* to the method of a slot. Constant references to fixed, final prop-
* erties can be compiled to direct access of the data value. This
* is the case with access to private, final or global variables.
*
* The instance and class hierarchies built at compile-time can be
* compressed into a single instance prototype and class object for
* faster lookup and dispatch.
*/
#ifndef ObjectValue_h
#define ObjectValue_h
#pragma warning( disable : 4786 )
#include <map>
#include <vector>
#include <string>
#include "Value.h"
#include "Type.h"
#include "Slot.h"
namespace esc {
namespace v1 {
class Context;
class TypeValue;
class Builder;
enum {
SLOT_PROTO = 0,
SLOT_CLASS,
SLOT_VALUE,
};
typedef std::map<Value*,int> Qualifiers;
typedef std::map<std::string,Qualifiers> Names;
typedef std::vector<Slot> Slots;
typedef std::vector<Value*> Namespaces;
class ObjectValue : public Value {
private:
Names names; // Names table
Slots slots; // Slots table
Slots dyna_slots; // Slots table
bool frozen_flag;
int first_index;
public:
static ObjectValue* undefinedValue;
static ObjectValue* nullValue;
static ObjectValue* trueValue;
static ObjectValue* falseValue;
static ObjectValue* publicNamespace;
static ObjectValue* objectPrototype;
ObjectValue();
ObjectValue(ObjectValue* protoObject);
ObjectValue(TypeValue* classObject);
ObjectValue(Builder& builder);
ObjectValue(bool value);
void ObjectValue::initInstance(ObjectValue* protoObject,TypeValue* classObject);
virtual ~ObjectValue() {
//names.clear();
//slots.clear();
//dyna_slots.clear();
}
/* Initialize and finalize the class.
*/
static void init();
static void fini();
/* Define a property and associate it with slot_index. Four forms:
* - maps a getter and setter name to a slot. This only works if
* the contents of the slot is an actual var index.
* - maps a getter name to a slot. The contents of the slot needs
* to be a code block that implements a getter.
* - maps a setter name to a slot. The contents of the slot needs
* to be a code blcok that implements a setter.
* - maps a method name to a slot. The contents of the slot needs
* to be a code block that implements a method.
*/
int define(Context& cx, std::string name, Value* qualifier, int slot_index);
// int defineGetter(Context& cx, std::string name, Value* qualifier, int slot_index);
// int defineSetter(Context& cx, std::string name, Value* qualifier, int slot_index);
// int defineMethod(Context& cx, std::string name, Value* qualifier, int slot_index);
/* Get the slot index of a property name
*/
int getSlotIndex(Context& cx, std::string name, Value* qualifier);
/* Get the slot of a property name
*/
Slot* get(Context& cx, std::string name, Value* qualifier);
/* Check for a property
*/
bool hasName(Context& cx, std::string name, Value* qualifier);
/* Check for names that consist of an id and one of multiple
* namespaces. Return a vector of namespaces that match. This
* method is used for lookup of unqualified names.
*/
Namespaces* hasNames(Context& cx, std::string name, Namespaces* namespaces);
/* Add a slot to this object.
*/
int addSlot(Context& cx);
/* Get a slot for a slot index
*/
Slot* getSlot(Context& cx, int index);
/* Check if the object is fixed yet.
*/
bool isFixed();
/* Get the start index for slots in this object. The indicies of
* all the objects in a prototype chain are contiguous.
*/
int getFirstSlotIndex();
/* Get the last slot index allocated for this part of the
* instance. Calling this method has the side-effect of
* freezing the slot table. Thereafter, new slots are
* allocated in the dynamic slots table.
*/
int getLastSlotIndex();
/* Get the [[Prototype]] object
*/
ObjectValue* proto(Context& cx);
/* Get the [[Type]] object
*/
virtual TypeValue* getType(Context& context);
// main
static int main(int argc, char* argv[]);
static int testClass(int argc, char* argv[]);
};
}
}
#endif // ObjectValue_h
/*
* Written by Jeff Dyer
* Copyright (c) 1998-2001 by Mountain View Compiler Company
* All rights reserved.
*/

View File

@@ -0,0 +1,11 @@
#pragma warning ( disable : 4786 )
#include "Token.h"
#include "States.h"
#include "Scanner.h"
#include "Parser.h"
namespace esc {
namespace v1 {
namespace parser {
}}}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,38 @@
#ifndef Slot_h
#define Slot_h
/*
* A slot.
*/
namespace esc {
namespace v1 {
class Value;
class ObjectValue;
struct Slot {
int attrs;
TypeValue* type;
union {
Value* value;
ObjectValue* objValue; // (ReferenceValue, ListValue, ObjectValue)
int intValue;
char* strValue;
};
Slot() : attrs(0), type(0), value(0) {
}
//Block block;
//Store store;
};
}
}
#endif // Slot_h
/*
* Copyright (c) 1998-2001 by Mountain View Compiler Company
* All rights reserved.
*/

View File

@@ -0,0 +1,35 @@
#ifndef Type_h
#define Type_h
/**
* The interface for all types.
*/
#include <vector>
namespace esc {
namespace v1 {
class Value;
class Context;
class Type {
// virtual std::vector<Value*> values() = 0;
// virtual std::vector<Value*> converts() = 0;
// virtual void addSub(Type& type) = 0;
virtual bool includes(Context& cx, Value* value) = 0;
// virtual void setSuper(Type& type) = 0;
// virtual Type* getSuper() = 0;
// virtual Value* convert(Context& cx, Value& value) = 0;
// virtual Value* coerce(Context& cx, Value& value) = 0;
};
}
}
#endif // Type_h
/*
* Copyright (c) 1998-2001 by Mountain View Compiler Company
* All rights reserved.
*/

View File

@@ -0,0 +1,19 @@
/*
* The value class from which all other values derive.
*/
#include "Scope.h"
#include "Value.h"
#include "Type.h"
namespace esc {
namespace v1 {
}
}
/*
* Written by Jeff Dyer
* Copyright (c) 1998-2001 by Mountain View Compiler Company
* All rights reserved.
*/

View File

@@ -0,0 +1,30 @@
#ifndef Value_h
#define Value_h
/*
* The value class from which all other values derive. Immediate
* children are ObjectValue, ReferenceValue, ListValue, and
* CompletionValue.
*/
namespace esc {
namespace v1 {
class Context;
class TypeValue;
class Value {
public:
virtual Value* getValue(Context& context) { return this; }
virtual TypeValue* getType(Context& context) { return (TypeValue*)0; }
};
}
}
#endif // Value_h
/*
* Copyright (c) 1998-2001 by Mountain View Compiler Company
* All rights reserved.
*/

View File

@@ -0,0 +1,119 @@
/*
* Global object builder
*/
#pragma warning ( disable : 4786 )
#include <string>
#include <map>
#include <algorithm>
#include "Context.h"
#include "Scope.h"
#include "Value.h"
#include "Type.h"
#include "Slot.h"
#include "Builder.h"
#include "GlobalObjectBuilder.h"
#include "TypeValue.h"
namespace esc {
namespace v1 {
void GlobalObjectBuilder::build(Context& cx, ObjectValue* ob) {
Slot* slot;
int slot_index;
// Never type
slot_index = ob->addSlot(cx);
slot_index = ob->define(cx,"Never",ObjectValue::publicNamespace,slot_index);
slot = ob->getSlot(cx,slot_index);
slot->objValue = new TypeValue();
// Null type
slot_index = ob->addSlot(cx);
slot_index = ob->define(cx,"Null",ObjectValue::publicNamespace,slot_index);
slot = ob->getSlot(cx,slot_index);
slot->objValue = new TypeValue();
// Boolean type
slot_index = ob->addSlot(cx);
slot_index = ob->define(cx,"Boolean",ObjectValue::publicNamespace,slot_index);
slot = ob->getSlot(cx,slot_index);
slot->objValue = new TypeValue();
// Number type
slot_index = ob->addSlot(cx);
slot_index = ob->define(cx,"Number",ObjectValue::publicNamespace,slot_index);
slot = ob->getSlot(cx,slot_index);
slot->objValue = new TypeValue();
// String type
slot_index = ob->addSlot(cx);
slot_index = ob->define(cx,"String",ObjectValue::publicNamespace,slot_index);
slot = ob->getSlot(cx,slot_index);
slot->objValue = new TypeValue();
// Function type
slot_index = ob->addSlot(cx);
slot_index = ob->define(cx,"Function",ObjectValue::publicNamespace,slot_index);
slot = ob->getSlot(cx,slot_index);
slot->objValue = new TypeValue();
// Array type
slot_index = ob->addSlot(cx);
slot_index = ob->define(cx,"Boolean",ObjectValue::publicNamespace,slot_index);
slot = ob->getSlot(cx,slot_index);
slot->objValue = new TypeValue();
// Type type
slot_index = ob->addSlot(cx);
slot_index = ob->define(cx,"Array",ObjectValue::publicNamespace,slot_index);
slot = ob->getSlot(cx,slot_index);
slot->objValue = new TypeValue();
// Unit type
slot_index = ob->addSlot(cx);
slot_index = ob->define(cx,"Unit",ObjectValue::publicNamespace,slot_index);
slot = ob->getSlot(cx,slot_index);
slot->objValue = new TypeValue();
// public namespace
slot_index = ob->addSlot(cx);
slot_index = ob->define(cx,"public",ObjectValue::publicNamespace,slot_index);
slot = ob->getSlot(cx,slot_index);
slot->value = ObjectValue::publicNamespace;
// print - (built-in) function
slot_index = ob->addSlot(cx);
slot_index = ob->define(cx,"print",ObjectValue::publicNamespace,slot_index);
slot = ob->getSlot(cx,slot_index);
slot->value = new ObjectValue(); // function: print
// version - (built-in) field
slot_index = ob->addSlot(cx);
slot_index = ob->define(cx,"get version",ObjectValue::publicNamespace,slot_index);
// slot_index = ob->defineGet(cx,"version",ObjectValue::publicNamespace,slot_index);
slot = ob->getSlot(cx,slot_index);
slot->intValue = 7; //value_count; // function: get version
slot_index = ob->addSlot(cx);
slot_index = ob->define(cx,"set version",ObjectValue::publicNamespace,slot_index);
// slot_index = ob->defineSet(cx,"version",ObjectValue::publicNamespace,slot_index);
slot = ob->getSlot(cx,slot_index);
slot->intValue = 7; //value_count++; // function: set version
}
}
}
/*
* Written by Jeff Dyer
* Copyright (c) 1998-2001 by Mountain View Compiler Company
* All rights reserved.
*/

View File

@@ -0,0 +1,35 @@
#ifndef GlobalObjectConstructor_h
#define GlobalObjectConstructor_h
/*
* Constructs global objects
*/
#include <string>
#include <vector>
#include "Builder.h"
#include "ObjectValue.h"
namespace esc {
namespace v1 {
class GlobalObjectBuilder : public Builder {
public:
GlobalObjectBuilder() {
}
virtual void build(Context& cx, ObjectValue* ob);
};
}
}
#endif // GlobalObjectConstructor_h
/*
* Written by Jeff Dyer
* Copyright (c) 1998-2001 by Mountain View Compiler Company
* All rights reserved
*/

View File

@@ -0,0 +1,536 @@
#pragma warning ( disable : 4786 )
#include <typeinfo>
#include "Nodes.h"
#include "ConstantEvaluator.h"
#include "NodeFactory.h"
#include "ReferenceValue.h"
#include "TypeValue.h"
#include "GlobalObjectBuilder.h"
namespace esc {
namespace v1 {
// Base node
Value* ConstantEvaluator::evaluate( Context& cx, Node* node ) {
throw;
}
/*
* Unqualified identifier
*
* STATUS
*
* NOTES
* An unqualified name can bind to a local variable, instance
* property, or global property. A local will result in a
* aload_n instruction. A instance property will result in a
* get_property method call. A global property will result in a
* get_property method call on the global object.
*/
Value* ConstantEvaluator::evaluate( Context& cx, IdentifierNode* node ) {
return new ReferenceValue((ObjectValue*)0,node->name,used_namespaces);
}
/*
* QualifiedIdentifierNode
*
* {qualifiers:QualifierListNode name:String}
*
* Semantics:
* 1. Evaluate qualifier.
* 2. Call GetValue(Result(1).
* 3. If Result(2) is not a namespace, then throw a TypeError.
* 4. Create a new Reference(null,Result2),name).
* 5. Return Result(4).
*/
Value* ConstantEvaluator::evaluate( Context& cx, QualifiedIdentifierNode* node ) {
Value* qualifier;
if( node->qualifier != (Node*)0 ) {
qualifier = node->qualifier->evaluate(cx,this);
qualifier = qualifier->getValue(cx);
}
if( qualifier == (Value*)0 ) {
//error();
throw;
}
else
if(!(TypeValue::namespaceType->includes(cx,qualifier)) ) {
//error();
throw;
}
return new ReferenceValue((ObjectValue*)0,node->name,qualifier);
}
/*
* CallExpression
*
* Semantics
* ---------
* 1 Evaluate MemberExpression.
* 2 Evaluate Arguments, producing an internal list of argument
* values (section 11.2.4).
* 3 Call GetValue(Result(1)).
* 4 If Type(Result(3)) is not Object, throw a TypeError exception.
* 5 If Result(3) does not implement the internal [[Call]] method,
* throw a TypeError exception.
* 6 If Type(Result(1)) is Reference, Result(6) is GetBase(Result(1)).
* Otherwise, Result(6) is null.
* 7 If Result(6) is an activation object, Result(7) is null.
* Otherwise, Result(7) is the same as Result(6).
* 8 Call the [[Call]] method on Result(3), providing Result(7)
* as the this value and providing the list Result(2) as the
* argument values.
* 9 Return Result(8).
*
*/
Value* ConstantEvaluator::evaluate( Context& cx, CallExpressionNode* node ) {
Value* val = node->member->evaluate(cx,this);
ReferenceValue* ref = dynamic_cast<ReferenceValue*>(val); // Forces the use of RTTI.
if( node->args ) {
node->args->evaluate(cx,this);
}
// Do typechecking. It is quite possible that this function has not
// yet been defined. In this case, all of the semantic actions must
// be performed at runtime.
if( ref->lookup(cx) ) {
/* If the function was found: The slot index is in
* ref->slot_index and the base object is presumed
* to be the top value on the operand stack (if base
* is set), otherwise it is the nth (ref->scope_index)
* object from the bottom of the scope stack. (0 is
* global.)
*
* Nothing to do here.
*/
}
node->ref = ref;
return ObjectValue::undefinedValue;
}
Value* ConstantEvaluator::evaluate( Context& cx, GetExpressionNode* node ) {
Value* val = node->member->evaluate(cx,this);
ReferenceValue* ref = dynamic_cast<ReferenceValue*>(val); // Forces the use of RTTI.
ref->name.insert(0,"get "); // Tweak the name to make it a getter reference.
// Do typechecking. It is quite possible that this function has not
// yet been defined. In this case, all of the semantic actions must
// be performed at runtime.
if( ref->lookup(cx) ) {
/* If the function was found: The slot index is in
* ref->slot_index and the base object is presumed
* to be the top value on the operand stack (if base
* is set), otherwise it is the nth (ref->scope_index)
* object from the bottom of the scope stack. (0 is
* global.)
*
* Nothing to do here.
*/
}
return node->ref = ref;
}
Value* ConstantEvaluator::evaluate( Context& cx, SetExpressionNode* node ) {
return 0;
}
Value* ConstantEvaluator::evaluate( Context& cx, ThisExpressionNode* node ) {
throw;
}
Value* ConstantEvaluator::evaluate( Context& cx, LiteralBooleanNode* node ) {
throw;
}
Value* ConstantEvaluator::evaluate( Context& cx, LiteralNumberNode* node ) {
return ObjectValue::undefinedValue;
}
Value* ConstantEvaluator::evaluate( Context& cx, LiteralStringNode* node ) {
return ObjectValue::undefinedValue;
}
Value* ConstantEvaluator::evaluate( Context& cx, LiteralUndefinedNode* node ) {
throw;
}
Value* ConstantEvaluator::evaluate( Context& cx, LiteralRegExpNode* node ) {
throw;
}
Value* ConstantEvaluator::evaluate( Context& cx, UnitExpressionNode* node ) {
if( node->value ) {
node->value->evaluate(cx,this);
}
if( node->type ) {
node->type->evaluate(cx,this);
}
return 0;
}
Value* ConstantEvaluator::evaluate( Context& cx, FunctionExpressionNode* node ) {
throw;
}
Value* ConstantEvaluator::evaluate( Context& cx, ParenthesizedExpressionNode* node ) {
throw;
}
Value* ConstantEvaluator::evaluate( Context& cx, ParenthesizedListExpressionNode* node ) {
throw;
}
Value* ConstantEvaluator::evaluate( Context& cx, LiteralObjectNode* node ) {
throw;
}
Value* ConstantEvaluator::evaluate( Context& cx, LiteralFieldNode* node ) {
throw;
}
Value* ConstantEvaluator::evaluate( Context& cx, LiteralArrayNode* node ) {
throw;
}
Value* ConstantEvaluator::evaluate( Context& cx, PostfixExpressionNode* node ) {
throw;
}
Value* ConstantEvaluator::evaluate( Context& cx, NewExpressionNode* node ) {
throw;
}
Value* ConstantEvaluator::evaluate( Context& cx, IndexedMemberExpressionNode* node ) {
throw;
}
Value* ConstantEvaluator::evaluate( Context& cx, ClassofExpressionNode* node ) {
throw;
}
Value* ConstantEvaluator::evaluate( Context& cx, MemberExpressionNode* node ) {
/* If the member expression has a base, evaluate it and try to
* bind it to its slot. If there it binds, then get the slot
* type and then the prototype of that type. The prototype will
* be the compile-time stand-in for the instance.
*/
ObjectValue* prototype = 0;
if( node->base ) {
Value* val = node->base->evaluate(cx,this);
ReferenceValue* ref = dynamic_cast<ReferenceValue*>(val); // Forces the use of RTTI.
Slot* slot = ref->getSlot(cx);
TypeValue* type = slot->type;
prototype = type->prototype;
}
ReferenceValue* ref = dynamic_cast<ReferenceValue*>(node->expr->evaluate(cx,this));
ref->setBase(prototype);
return ref;
}
Value* ConstantEvaluator::evaluate( Context& cx, CoersionExpressionNode* node ) {
throw;
}
Value* ConstantEvaluator::evaluate( Context& cx, UnaryExpressionNode* node ) {
throw;
}
Value* ConstantEvaluator::evaluate( Context& cx, BinaryExpressionNode* node ) {
throw;
}
Value* ConstantEvaluator::evaluate( Context& cx, ConditionalExpressionNode* node ) {
throw;
}
Value* ConstantEvaluator::evaluate( Context& cx, AssignmentExpressionNode* node ) {
throw;
}
Value* ConstantEvaluator::evaluate( Context& cx, ListNode* node ) {
if( node->list ) {
node->list->evaluate(cx,this);
}
if( node->item ) {
// If it is a member expression convert it to a get expression.
node->item->evaluate(cx,this);
}
return ObjectValue::undefinedValue;
}
// Statements
Value* ConstantEvaluator::evaluate( Context& cx, StatementListNode* node ) {
if( node->list ) {
node->list->evaluate(cx,this);
}
if( node->item ) {
node->item->evaluate(cx,this);
}
return ObjectValue::undefinedValue;
}
Value* ConstantEvaluator::evaluate( Context& cx, EmptyStatementNode* node ) {
throw;
}
Value* ConstantEvaluator::evaluate( Context& cx, ExpressionStatementNode* node ) {
Value* result = 0;
if( node->expr ) {
result = node->expr->evaluate(cx,this);
}
return result;
}
Value* ConstantEvaluator::evaluate( Context& cx, AnnotatedBlockNode* node ) {
throw;
}
Value* ConstantEvaluator::evaluate( Context& cx, LabeledStatementNode* node ) {
throw;
}
Value* ConstantEvaluator::evaluate( Context& cx, IfStatementNode* node ) {
throw;
}
Value* ConstantEvaluator::evaluate( Context& cx, SwitchStatementNode* node ) {
throw;
}
Value* ConstantEvaluator::evaluate( Context& cx, CaseLabelNode* node ) {
throw;
}
Value* ConstantEvaluator::evaluate( Context& cx, DoStatementNode* node ) {
throw;
}
Value* ConstantEvaluator::evaluate( Context& cx, WhileStatementNode* node ) {
throw;
}
Value* ConstantEvaluator::evaluate( Context& cx, ForInStatementNode* node ) {
throw;
}
Value* ConstantEvaluator::evaluate( Context& cx, ForStatementNode* node ) {
throw;
}
Value* ConstantEvaluator::evaluate( Context& cx, WithStatementNode* node ) {
throw;
}
Value* ConstantEvaluator::evaluate( Context& cx, ContinueStatementNode* node ) {
throw;
}
Value* ConstantEvaluator::evaluate( Context& cx, BreakStatementNode* node ) {
throw;
}
Value* ConstantEvaluator::evaluate( Context& cx, ReturnStatementNode* node ) {
throw;
}
Value* ConstantEvaluator::evaluate( Context& cx, ThrowStatementNode* node ) {
throw;
}
Value* ConstantEvaluator::evaluate( Context& cx, TryStatementNode* node ) {
throw;
}
Value* ConstantEvaluator::evaluate( Context& cx, CatchClauseNode* node ) {
throw;
}
Value* ConstantEvaluator::evaluate( Context& cx, FinallyClauseNode* node ) {
throw;
}
Value* ConstantEvaluator::evaluate( Context& cx, UseStatementNode* node ) {
throw;
}
Value* ConstantEvaluator::evaluate( Context& cx, IncludeStatementNode* node ) {
throw;
}
// Definitions
Value* ConstantEvaluator::evaluate( Context& cx, ImportDefinitionNode* node ) {
throw;
}
Value* ConstantEvaluator::evaluate( Context& cx, ImportBindingNode* node ) {
throw;
}
Value* ConstantEvaluator::evaluate( Context& cx, AnnotatedDefinitionNode* node ) {
Value* result;
if( node->attributes ) {
// modifier_attributes = node->attributes->evaluate(cx,this);
// if( modifier_attributes.getValue(context)==BooleanValue.falseValue ) {
// return UndefinedValue.undefinedValue;
// }
}
result = node->definition->evaluate(cx,this);
return result;
}
Value* ConstantEvaluator::evaluate( Context& cx, AttributeListNode* node ) {
throw;
}
Value* ConstantEvaluator::evaluate( Context& cx, ExportDefinitionNode* node ) {
throw;
}
Value* ConstantEvaluator::evaluate( Context& cx, ExportBindingNode* node ) {
throw;
}
Value* ConstantEvaluator::evaluate( Context& cx, VariableDefinitionNode* node ) {
throw;
}
Value* ConstantEvaluator::evaluate( Context& cx, VariableBindingNode* node ) {
throw;
}
Value* ConstantEvaluator::evaluate( Context& cx, TypedVariableNode* node ) {
throw;
}
Value* ConstantEvaluator::evaluate( Context& cx, FunctionDefinitionNode* node ) {
throw;
}
Value* ConstantEvaluator::evaluate( Context& cx, FunctionDeclarationNode* node ) {
throw;
}
Value* ConstantEvaluator::evaluate( Context& cx, FunctionNameNode* node ) {
throw;
}
Value* ConstantEvaluator::evaluate( Context& cx, FunctionSignatureNode* node ) {
throw;
}
Value* ConstantEvaluator::evaluate( Context& cx, ParameterNode* node ) {
throw;
}
Value* ConstantEvaluator::evaluate( Context& cx, OptionalParameterNode* node ) {
throw;
}
Value* ConstantEvaluator::evaluate( Context& cx, ClassDefinitionNode* node ) {
throw;
}
Value* ConstantEvaluator::evaluate( Context& cx, ClassDeclarationNode* node ) {
throw;
}
Value* ConstantEvaluator::evaluate( Context& cx, InheritanceNode* node ) {
throw;
}
Value* ConstantEvaluator::evaluate( Context& cx, NamespaceDefinitionNode* node ) {
throw;
}
Value* ConstantEvaluator::evaluate( Context& cx, PackageDefinitionNode* node ) {
throw;
}
Value* ConstantEvaluator::evaluate( Context& cx, ProgramNode* node ) {
if( node->statements ) {
node->statements->evaluate(cx,this);
}
return (Value*)0;
}
/*
* Test driver
*/
int ConstantEvaluator::main(int argc, char* argv[]) {
std::ofstream err("ConstantEvaluator.err");
Context cx(err);
Evaluator* evaluator = new ConstantEvaluator();
Builder* globalObjectBuilder = new GlobalObjectBuilder();
ObjectValue* globalPrototype = new ObjectValue(*globalObjectBuilder);
ObjectValue global = ObjectValue(globalPrototype);
cx.pushScope(&global); // first scope is always considered the global scope.
cx.used_namespaces.push_back(ObjectValue::publicNamespace);
Node* node;
Value* val;
// public::print
node = NodeFactory::QualifiedIdentifier(
NodeFactory::Identifier("public"),
NodeFactory::Identifier("print"));
val = node->evaluate(cx,evaluator);
val = val->getValue(cx);
// get version
node = NodeFactory::GetExpression(
NodeFactory::MemberExpression(0,
NodeFactory::Identifier("version")));
val = node->evaluate(cx,evaluator);
val = val->getValue(cx);
// print('hello')
node = NodeFactory::CallExpression(NodeFactory::MemberExpression(0,NodeFactory::Identifier("print")),0);
val = node->evaluate(cx,evaluator);
val = val->getValue(cx);
return 0;
}
}
}
/*
* Written by Jeff Dyer
* Copyright (c) 1998-2001 by Mountain View Compiler Company
* All rights reserved.
*/

View File

@@ -0,0 +1,125 @@
/*
* ConstantEvaluator
*/
#ifndef ConstantEvaluator_h
#define ConstantEvaluator_h
#include <vector>
#include "Value.h"
#include "Context.h"
#include "Evaluator.h"
#include "ObjectValue.h"
#include "ByteCodeFactory.h"
//#include "ClassFileConstants.h"
namespace esc {
namespace v1 {
class ConstantEvaluator : public Evaluator {
std::vector<Value*>* used_namespaces;
public:
/*
* Test driver
*/
static int main(int argc, char* argv[]);
// Base node
Value* evaluate( Context& cx, Node* node );
// 3rd Edition features
Value* evaluate( Context& cx, IdentifierNode* node );
Value* evaluate( Context& cx, ThisExpressionNode* node );
Value* evaluate( Context& cx, LiteralBooleanNode* node );
Value* evaluate( Context& cx, LiteralNumberNode* node );
Value* evaluate( Context& cx, LiteralStringNode* node );
Value* evaluate( Context& cx, LiteralUndefinedNode* node );
Value* evaluate( Context& cx, LiteralRegExpNode* node );
Value* evaluate( Context& cx, FunctionExpressionNode* node );
Value* evaluate( Context& cx, ParenthesizedExpressionNode* node );
Value* evaluate( Context& cx, ParenthesizedListExpressionNode* node );
Value* evaluate( Context& cx, LiteralObjectNode* node );
Value* evaluate( Context& cx, LiteralFieldNode* node );
Value* evaluate( Context& cx, LiteralArrayNode* node );
Value* evaluate( Context& cx, PostfixExpressionNode* node );
Value* evaluate( Context& cx, NewExpressionNode* node );
Value* evaluate( Context& cx, IndexedMemberExpressionNode* node );
Value* evaluate( Context& cx, MemberExpressionNode* node );
Value* evaluate( Context& cx, CallExpressionNode* node );
Value* evaluate( Context& cx, GetExpressionNode* node );
Value* evaluate( Context& cx, SetExpressionNode* node );
Value* evaluate( Context& cx, UnaryExpressionNode* node );
Value* evaluate( Context& cx, BinaryExpressionNode* node );
Value* evaluate( Context& cx, ConditionalExpressionNode* node );
Value* evaluate( Context& cx, AssignmentExpressionNode* node );
Value* evaluate( Context& cx, ListNode* node );
Value* evaluate( Context& cx, StatementListNode* node );
Value* evaluate( Context& cx, EmptyStatementNode* node );
Value* evaluate( Context& cx, ExpressionStatementNode* node );
Value* evaluate( Context& cx, AnnotatedBlockNode* node );
Value* evaluate( Context& cx, LabeledStatementNode* node );
Value* evaluate( Context& cx, IfStatementNode* node );
Value* evaluate( Context& cx, SwitchStatementNode* node );
Value* evaluate( Context& cx, CaseLabelNode* node );
Value* evaluate( Context& cx, DoStatementNode* node );
Value* evaluate( Context& cx, WhileStatementNode* node );
Value* evaluate( Context& cx, ForInStatementNode* node );
Value* evaluate( Context& cx, ForStatementNode* node );
Value* evaluate( Context& cx, WithStatementNode* node );
Value* evaluate( Context& cx, ContinueStatementNode* node );
Value* evaluate( Context& cx, BreakStatementNode* node );
Value* evaluate( Context& cx, ReturnStatementNode* node );
Value* evaluate( Context& cx, ThrowStatementNode* node );
Value* evaluate( Context& cx, TryStatementNode* node );
Value* evaluate( Context& cx, CatchClauseNode* node );
Value* evaluate( Context& cx, FinallyClauseNode* node );
Value* evaluate( Context& cx, AnnotatedDefinitionNode* node );
Value* evaluate( Context& cx, VariableDefinitionNode* node );
Value* evaluate( Context& cx, VariableBindingNode* node );
Value* evaluate( Context& cx, FunctionDefinitionNode* node );
Value* evaluate( Context& cx, FunctionDeclarationNode* node );
Value* evaluate( Context& cx, FunctionNameNode* node );
Value* evaluate( Context& cx, FunctionSignatureNode* node );
Value* evaluate( Context& cx, ParameterNode* node );
Value* evaluate( Context& cx, ProgramNode* node );
// 4th Edition features
Value* evaluate( Context& cx, QualifiedIdentifierNode* node );
Value* evaluate( Context& cx, UnitExpressionNode* node );
Value* evaluate( Context& cx, ClassofExpressionNode* node );
Value* evaluate( Context& cx, CoersionExpressionNode* node );
Value* evaluate( Context& cx, UseStatementNode* node );
Value* evaluate( Context& cx, IncludeStatementNode* node );
Value* evaluate( Context& cx, ImportDefinitionNode* node );
Value* evaluate( Context& cx, ImportBindingNode* node );
Value* evaluate( Context& cx, AttributeListNode* node );
Value* evaluate( Context& cx, ExportDefinitionNode* node );
Value* evaluate( Context& cx, ExportBindingNode* node );
Value* evaluate( Context& cx, TypedVariableNode* node );
Value* evaluate( Context& cx, OptionalParameterNode* node );
Value* evaluate( Context& cx, ClassDefinitionNode* node );
Value* evaluate( Context& cx, ClassDeclarationNode* node );
Value* evaluate( Context& cx, InheritanceNode* node );
Value* evaluate( Context& cx, NamespaceDefinitionNode* node );
Value* evaluate( Context& cx, PackageDefinitionNode* node );
};
}
}
#endif // ConstantEvaluator_h
/*
* Copyright (c) 1998-2001 by Mountain View Compiler Company
* All rights reserved.
*/

View File

@@ -0,0 +1,215 @@
/*
* ReferenceValue
*/
#pragma warning ( disable : 4786 )
#include <stack>
#include "ReferenceValue.h"
#include "TypeValue.h"
#include "ObjectValue.h"
#include "Context.h"
namespace esc {
namespace v1 {
ReferenceValue::ReferenceValue(ObjectValue* base, std::string name,
Value* qualifier)
: base(base), name(name), qualifier(qualifier),
used_namespaces((std::vector<Value*>*)0), slot((Slot*)0),
slot_index(0),scope_index(0) {
}
ReferenceValue::ReferenceValue(ObjectValue* base, std::string name,
std::vector<Value*>* used_namespaces)
: base(base), name(name), qualifier((Value*)0),
used_namespaces(used_namespaces), slot((Slot*)0),
slot_index(0),scope_index(0) {
}
Value* ReferenceValue::getValue(Context& cx) {
Slot* s = this->getSlot(cx);
if( s ) {
return s->value;
} else {
return (Value*)0;
}
}
Slot* ReferenceValue::getSlot(Context& cx) {
if( slot ) {
return slot;
}
if( lookup(cx) ) {
// lookup has the side-effect of binding
// this reference to its defining slot. So
// now just return it.
return this->slot;
} else {
return (Slot*)0;
}
}
/*
* Lookup qualified name in the given context.
*/
bool ReferenceValue::lookup(Context& cx) {
ObjectValue* obj;
if(!base) {
// If there is no base reference, search for the
// binding from the inside to the outside of the
// scope chain. Fix up this reference's base member
// and recurse.
std::stack<ObjectValue*> scopes = cx.getScopes();
int scope_index = 0;
while( scopes.size() ) {
this->base = scopes.top(); // Set the base value
if( this->lookup(cx) ) {
// Found one. Clear the temporary base value
// and set the scope index.
this->base = 0;
this->scope_index = scope_index;
break;
}
scopes.pop();
++scope_index;
}
} else {
// If there is a base reference, search for the
// binding in this object and then up the proto
// chain.
if(!qualifier) {
return this->lookupUnqualified(cx);
}
obj = base;
while(obj && !obj->hasName(cx,name,qualifier)) {
obj = obj->proto(cx);
}
if( !obj ) {
return false;
}
// Bind slot
this->slot_index = obj->getSlotIndex(cx,name,qualifier);
this->slot = obj->getSlot(cx,this->slot_index);
}
return true;
}
/*
* Lookup a name that has one of the used namespaces.
*
* 1 Traverse to root of proto chain, pushing all objects
* onto a temporary stack.
* 2 In lifo order, see if one or more of the qualified
* names represented by the name and the used qualfiers
* is in the top object on the stack. Repeat for all
* objects on the stack until one object with at least
* one match is found, or all objects have been searched.
* 3 Create a new set of namespaces that inclues all
* the qualifiers of all the names that matched in the
* previous step.
* 4 Starting with the most derived object, search to
* proto chain for one or more of the qualified names
* represented by the name and the new set of used
* qualifiers.
* 5 If the found set represents more than one slot, throw
* and error exception. Otherwise, return true.
* 6 If no matching names are found, return false.
*/
bool ReferenceValue::lookupUnqualified(Context& cx) {
// Search this object and up the inheritance chain
// to find the qualified name.
ObjectValue* obj = base;
// Push the protos onto a stack.
std::stack<ObjectValue*> protos;
while(obj) {
protos.push(obj);
obj = obj->proto(cx);
}
// Search the protos top-down for matching names.
Namespaces* namespaces = 0;
while(!protos.empty()) {
ObjectValue* obj = protos.top();
namespaces = obj->hasNames(cx,name,&cx.used_namespaces);
if( namespaces ) {
break;
}
protos.pop();
}
// If no namespaces, then no matches. Return false.
if( !namespaces ) {
return false;
}
// Search for the first object in the proto chain that
// matches the name and namespaces.
obj = base?base:cx.scope();
while(obj && !(obj->hasNames(cx,name,namespaces))) {
obj = obj->proto(cx);
}
if( !obj ) {
return false;
}
// Verify that all matched names point to a single slot.
int last_index = 0;
for( int i = 0; i < namespaces->size(); i++ ) {
Value* qualifier = namespaces->at(i);
int index = obj->getSlotIndex(cx,name,qualifier);
if( last_index!=0 && index!=last_index ) {
throw;
// error();
}
last_index = index;
}
// Bind slot
this->slot_index = last_index;
this->slot = obj->getSlot(cx,this->slot_index);
return true;
}
}
}
/*
* Written by Jeff Dyer
* Copyright (c) 1998-2001 by Mountain View Compiler Company
* All rights reserved.
*/

View File

@@ -0,0 +1,58 @@
/*
* ReferenceValue
*/
#ifndef ReferenceValue_h
#define ReferenceValue_h
#pragma warning( disable : 4786 )
#include <string>
#include <vector>
#include "Value.h"
namespace esc {
namespace v1 {
struct Slot;
class ObjectValue;
class Context;
class ReferenceValue : public Value {
ObjectValue* base;
Value* qualifier;
std::vector<Value*>* used_namespaces;
Slot* slot;
int slot_index;
int scope_index;
public:
std::string name;
ReferenceValue(ObjectValue* base, std::string name, Value* qualifier);
ReferenceValue(ObjectValue* base, std::string name, std::vector<Value*>* used_namespaces);
bool lookup(Context& cx);
bool lookupUnqualified(Context& cx);
Slot* getSlot(Context& cx);
Value* getValue(Context& cx);
int getSlotIndex() { return slot_index; }
int getScopeIndex() { return scope_index; }
ReferenceValue* setBase(ObjectValue* base) { this->base = base; return this; }
// main
static int main(int argc, char* argv[]);
};
}
}
#endif // ReferenceValue_h
/*
* Copyright (c) 1998-2001 by Mountain View Compiler Company
* All rights reserved.
*/

View File

@@ -0,0 +1,83 @@
/*
* The value class from which all other values derive.
*/
#pragma warning ( disable : 4786 )
#include <string>
#include <map>
#include <algorithm>
#include "Context.h"
#include "Scope.h"
#include "Value.h"
#include "Type.h"
#include "Slot.h"
#include "Builder.h"
#include "TypeValue.h"
namespace esc {
namespace v1 {
bool TypeValue::isInitialized = false;
TypeValue* TypeValue::booleanType;
TypeValue* TypeValue::namespaceType;
TypeValue* TypeValue::objectType;
TypeValue* TypeValue::typeType;
void TypeValue::init() {
if( isInitialized ) {
return;
}
isInitialized = true;
booleanType = new TypeValue();
namespaceType = new TypeValue();
objectType = new TypeValue();
typeType = new TypeValue();
}
void TypeValue::fini() {
if( isInitialized ) {
delete typeType;
delete objectType;
delete namespaceType;
delete booleanType;
isInitialized = false;
}
}
bool TypeValue::includes(Context& cx, Value* value) {
TypeValue* type = value->getType(cx);
while( type ) {
if( type == this ) {
return true;
}
type = type->super(cx);
}
return false;
}
void TypeValue::build(Context& cx, ObjectValue* ob) {
}
TypeValue* TypeValue::super(Context& cx) {
return reinterpret_cast<TypeValue*>(this->proto(cx));
}
}
}
/*
* Written by Jeff Dyer
* Copyright (c) 1998-2001 by Mountain View Compiler Company
* All rights reserved.
*/

View File

@@ -0,0 +1,58 @@
#ifndef TypeValue_h
#define TypeValue_h
/**
* The interface for all types.
*/
#include <vector>
#include "Builder.h"
#include "ObjectValue.h"
namespace esc {
namespace v1 {
class TypeValue : public ObjectValue, public Type, public Builder {
static bool isInitialized;
public:
ObjectValue* prototype;
virtual bool includes(Context& cx, Value* value);
virtual void build(Context& cx, ObjectValue* ob);
TypeValue* super(Context& cx);
TypeValue() {
this->prototype = new ObjectValue();
}
static TypeValue* booleanType;
static TypeValue* namespaceType;
static TypeValue* objectType;
static TypeValue* typeType;
#if 0
virtual std::vector<Value*> values() {};
virtual std::vector<Value*> converts() {};
virtual void addSub(Type& type) {};
virtual void setSuper(Type& type) {};
virtual Type* getSuper(){};
virtual Value* convert(Context& cx, Value& value) {};
virtual Value* coerce(Context& cx, Value& value) {};
#endif
static void init();
static void fini();
};
}
}
#endif // TypeValue_h
/*
* Copyright (c) 1998-2001 by Mountain View Compiler Company
* All rights reserved.
*/

View File

@@ -0,0 +1,10 @@
#include "Debugger.h"
namespace esc {
namespace v1 {
std::ofstream* Debugger::dbg;
std::ofstream* Debugger::dbg_prev;
}
}

View File

@@ -0,0 +1,82 @@
#ifndef Debugger_h
#define Debugger_h
#include <fstream>
namespace esc {
namespace v1 {
struct Debugger {
static std::ofstream* dbg_prev;
static std::ofstream* dbg;
static void trace(std::string str) {
*dbg << str.c_str() << '\n';
}
static void trace(const char* str) {
*dbg << str << '\n';
}
static void trace(const char* str1, const char* str2) {
*dbg << str1 << str2 << '\n';
}
static void init(std::ofstream* ds) {
dbg_prev = dbg;
dbg = ds;
}
static void reset() {
dbg = dbg_prev;
}
#if 0
public static PrintStream dbg = null;
private static boolean useSystemOut = false;
public static void setOutFile(String filename) {
try {
PrintStream out = new PrintStream( new FileOutputStream( filename ) );
System.setOut( out );
//System.setErr( outfile );
} catch ( Exception e ) {
e.printStackTrace();
}
}
public static void setErrFile(String filename) {
try {
PrintStream err = new PrintStream( new FileOutputStream( filename ) );
//System.setOut( out );
System.setErr( err );
} catch ( Exception e ) {
e.printStackTrace();
}
}
public static void setDbgFile(String filename) {
try {
if( dbg!=null) {
dbg.close();
}
dbg = new PrintStream( new FileOutputStream( filename ) );
//System.setOut( outfile );
//System.setErr( outfile );
} catch ( Exception e ) {
e.printStackTrace();
}
}
#endif
};
}
}
#endif // Debugger_h
/*
* Written by Jeff Dyer
* Copyright (c) 1998-2001 by Mountain View Compiler Company.
* All Rights Reserved.
*/

View File

@@ -0,0 +1,925 @@
package com.compilercompany.es3c.v1;
import java.io.*;
/**
* JSILGenerator
*/
public class JSILGenerator extends Evaluator implements Tokens {
public static boolean debug = false;
private static PrintStream out;
public static void setOut(String filename) throws Exception {
out = new PrintStream( new FileOutputStream(filename) );
}
private static void emit(String str) {
if( debug ) {
Debugger.trace("emit " + str);
}
if( out!=null ) {
out.println(str);
}
else {
}
}
Value evaluate( Context context, Node node ) throws Exception {
String tag = "missing evaluator for " + node.getClass(); emit(context.getIndent()+tag); return null;
}
// Expression evaluators
Value evaluate( Context context, ThisExpressionNode node ) throws Exception {
String tag = "ThisExpression ";
emit(context.getIndent()+tag);
return null;
}
Value evaluate( Context context, IdentifierNode node ) throws Exception {
String tag = "Identifier ";
emit(context.getIndent()+tag);
context.indent++;
if( node.name != null ) {
emit(context.getIndent()+node.name);
}
context.indent--;
return null;
}
Value evaluate( Context context, QualifiedIdentifierNode node ) throws Exception {
String tag = "QualifiedIdentifier ";
emit(context.getIndent()+tag);
context.indent++;
if( node.qualifier != null ) {
node.qualifier.evaluate(context,this);
}
if( node.name != null ) {
emit(context.getIndent()+node.name);
}
context.indent--;
return null;
}
Value evaluate( Context context, LiteralBooleanNode node ) throws Exception {
String tag = "LiteralBoolean: " + node.value;
emit(context.getIndent()+tag);
return null;
}
Value evaluate( Context context, LiteralNullNode node ) throws Exception {
String tag = "LiteralNull ";
emit(context.getIndent()+tag);
return null;
}
Value evaluate( Context context, LiteralNumberNode node ) throws Exception {
String tag = "LiteralNumber: " + node.value;
emit(context.getIndent()+tag);
return null;
}
Value evaluate( Context context, LiteralStringNode node ) throws Exception {
String tag = "LiteralString: " + node.value;
emit(context.getIndent()+tag);
return null;
}
Value evaluate( Context context, LiteralUndefinedNode node ) throws Exception {
String tag = "LiteralUndefined ";
emit(context.getIndent()+tag);
return null;
}
Value evaluate( Context context, LiteralRegExpNode node ) throws Exception {
String tag = "LiteralRegExp: " + node.value;
emit(context.getIndent()+tag);
return null;
}
Value evaluate( Context context, UnitExpressionNode node ) throws Exception {
String tag = "UnitExpression ";
emit(context.getIndent()+tag);
context.indent++;
if( node.value != null ) {
node.value.evaluate(context,this);
}
if( node.type != null ) {
node.type.evaluate(context,this);
}
context.indent--;
return null;
}
Value evaluate( Context context, ParenthesizedExpressionNode node ) throws Exception {
String tag = "ParenthesizedExpression ";
emit(context.getIndent()+tag);
context.indent++;
if( node.expr != null ) {
node.expr.evaluate(context,this);
}
context.indent--;
return null;
}
Value evaluate( Context context, ParenthesizedListExpressionNode node ) throws Exception {
String tag = "ParenthesizedListExpression ";
emit(context.getIndent()+tag);
context.indent++;
if( node.expr != null ) {
node.expr.evaluate(context,this);
}
context.indent--;
return null;
}
Value evaluate( Context context, FunctionExpressionNode node ) throws Exception {
String tag = "FunctionExpression ";
emit(context.getIndent()+tag);
context.indent++;
if( node.name != null ) {
node.name.evaluate(context,this);
}
if( node.signature != null ) {
node.signature.evaluate(context,this);
}
if( node.body != null ) {
node.body.evaluate(context,this);
}
context.indent--;
return null;
}
Value evaluate( Context context, LiteralObjectNode node ) throws Exception {
String tag = "LiteralObject ";
emit(context.getIndent()+tag);
context.indent++;
if( node.fieldlist != null ) {
node.fieldlist.evaluate(context,this);
}
context.indent--;
return null;
}
Value evaluate( Context context, LiteralFieldNode node ) throws Exception {
String tag = "LiteralField ";
emit(context.getIndent()+tag);
context.indent++;
if( node.name != null ) {
node.name.evaluate(context,this);
}
if( node.value != null ) {
node.value.evaluate(context,this);
}
context.indent--;
return null;
}
Value evaluate( Context context, LiteralArrayNode node ) throws Exception {
String tag = "LiteralArray ";
emit(context.getIndent()+tag);
context.indent++;
if( node.elementlist != null ) {
node.elementlist.evaluate(context,this);
}
context.indent--;
return null;
}
Value evaluate( Context context, PostfixExpressionNode node ) throws Exception {
String tag = "PostfixExpression: " + Token.getTokenClassName(node.op);
emit(context.getIndent()+tag);
context.indent++;
if( node.expr != null ) {
node.expr.evaluate(context,this);
}
context.indent--;
return null;
}
Value evaluate( Context context, NewExpressionNode node ) throws Exception {
String tag = "NewExpression";
emit(context.getIndent()+tag);
context.indent++;
if( node.expr != null ) {
node.expr.evaluate(context,this);
}
context.indent--;
return null;
}
Value evaluate( Context context, IndexedMemberExpressionNode node ) throws Exception {
String tag = "IndexedMemberExpression";
emit(context.getIndent()+tag);
context.indent++;
if( node.base != null ) {
node.base.evaluate(context,this);
}
if( node.expr != null ) {
node.expr.evaluate(context,this);
}
context.indent--;
return null;
}
Value evaluate( Context context, MemberExpressionNode node ) throws Exception {
String tag = "MemberExpression";
emit(context.getIndent()+tag);
context.indent++;
if( node.base != null ) {
node.base.evaluate(context,this);
}
if( node.name != null ) {
node.name.evaluate(context,this);
}
context.indent--;
return null;
}
Value evaluate( Context context, ClassofExpressionNode node ) throws Exception {
String tag = "ClassofExpression";
emit(context.getIndent()+tag);
context.indent++;
if( node.base != null ) {
node.base.evaluate(context,this);
}
context.indent--;
return null;
}
Value evaluate( Context context, CoersionExpressionNode node ) throws Exception {
String tag = "CoersionExpression";
emit(context.getIndent()+tag);
context.indent++;
if( node.expr != null ) {
node.expr.evaluate(context,this);
}
if( node.type != null ) {
node.type.evaluate(context,this);
}
context.indent--;
return null;
}
Value evaluate( Context context, CallExpressionNode node ) throws Exception {
String tag = "CallExpression";
emit(context.getIndent()+tag);
context.indent++;
if( node.member != null ) {
node.member.evaluate(context,this);
}
if( node.args != null ) {
node.args.evaluate(context,this);
}
context.indent--;
return null;
}
Value evaluate( Context context, UnaryExpressionNode node ) throws Exception {
String tag = "UnaryExpression: " + Token.getTokenClassName(node.op);
emit(context.getIndent()+tag);
context.indent++;
if( node.expr != null ) {
node.expr.evaluate(context,this);
}
context.indent--;
return null;
}
Value evaluate( Context context, BinaryExpressionNode node ) throws Exception {
String tag = "BinaryExpression: " + Token.getTokenClassName(node.op);
emit(context.getIndent()+tag);
context.indent++;
if( node.lhs != null ) {
node.lhs.evaluate(context,this);
}
if( node.rhs != null ) {
node.rhs.evaluate(context,this);
}
context.indent--;
return null;
}
Value evaluate( Context context, ConditionalExpressionNode node ) throws Exception {
String tag = "ConditionalExpression";
emit(context.getIndent()+tag);
context.indent++;
if( node.condition != null ) {
node.condition.evaluate(context,this);
}
if( node.thenexpr != null ) {
node.thenexpr.evaluate(context,this);
}
if( node.elseexpr != null ) {
node.elseexpr.evaluate(context,this);
}
context.indent--;
return null;
}
Value evaluate( Context context, AssignmentExpressionNode node ) throws Exception {
String tag = "AssignmentExpression: " + ((node.op==empty_token)?"":Token.getTokenClassName(node.op));
emit(context.getIndent()+tag);
context.indent++;
if( node.lhs != null ) {
node.lhs.evaluate(context,this);
}
if( node.rhs != null ) {
node.rhs.evaluate(context,this);
}
context.indent--;
return null;
}
Value evaluate( Context context, ListNode node ) throws Exception {
String tag = "List";
//emit(context.getIndent()+tag);
if( node.list != null ) {
node.list.evaluate(context,this);
}
if( node.item != null ) {
node.item.evaluate(context,this);
}
return null;
}
// Statements
Value evaluate( Context context, StatementListNode node ) throws Exception {
String tag = "StatementList";
//emit(context.getIndent()+tag);
if( node.list != null ) {
node.list.evaluate(context,this);
}
if( node.item != null ) {
node.item.evaluate(context,this);
}
return null;
}
Value evaluate( Context context, EmptyStatementNode node ) throws Exception {
String tag = (node.isLeader ? "*"+node.block+":" : ""+node.block+": ")+"EmptyStatement";
emit(context.getIndent()+tag);
return null;
}
Value evaluate( Context context, ExpressionStatementNode node ) throws Exception {
String tag = (node.isLeader ? "*"+node.block+":" : ""+node.block+": ")+"ExpressionStatement";
emit(context.getIndent()+tag);
context.indent++;
if( node.expr != null ) {
node.expr.evaluate(context,this);
}
context.indent--;
return null;
}
Value evaluate( Context context, AnnotatedBlockNode node ) throws Exception {
String tag = (node.isLeader ? "*"+node.block+":" : ""+node.block+": ")+"AnnotatedBlock";
emit(context.getIndent()+tag);
context.indent++;
if( node.attributes != null ) {
node.attributes.evaluate(context,this);
}
if( node.statements != null ) {
node.statements.evaluate(context,this);
}
context.indent--;
return null;
}
Value evaluate( Context context, LabeledStatementNode node ) throws Exception {
String tag = (node.isLeader ? "*"+node.block+":" : ""+node.block+": ")+"LabeledStatement";
emit(context.getIndent()+tag);
context.indent++;
if( node.label != null ) {
node.label.evaluate(context,this);
}
if( node.statement != null ) {
node.statement.evaluate(context,this);
}
context.indent--;
return null;
}
Value evaluate( Context context, IfStatementNode node ) throws Exception {
String tag = (node.isLeader ? "*"+node.block+":" : ""+node.block+": ")+"IfStatement";
emit(context.getIndent()+tag);
context.indent++;
if( node.condition != null ) {
node.condition.evaluate(context,this);
}
if( node.thenactions != null ) {
node.thenactions.evaluate(context,this);
}
if( node.elseactions != null ) {
node.elseactions.evaluate(context,this);
}
context.indent--;
return null;
}
Value evaluate( Context context, SwitchStatementNode node ) throws Exception {
String tag = (node.isLeader ? "*"+node.block+":" : ""+node.block+": ")+"SwitchStatement";
emit(context.getIndent()+tag);
context.indent++;
if( node.expr != null ) {
node.expr.evaluate(context,this);
}
if( node.statements != null ) {
node.statements.evaluate(context,this);
}
context.indent--;
return null;
}
Value evaluate( Context context, CaseLabelNode node ) throws Exception {
String tag = (node.isLeader ? "*"+node.block+":" : ""+node.block+": ")+"CaseLabel";
emit(context.getIndent()+tag);
context.indent++;
if( node.label != null ) {
node.label.evaluate(context,this);
} else {
emit(context.getIndent()+"default");
}
context.indent--;
return null;
}
Value evaluate( Context context, DoStatementNode node ) throws Exception {
String tag = (node.isLeader ? "*"+node.block+":" : ""+node.block+": ")+"DoStatement";
emit(context.getIndent()+tag);
context.indent++;
if( node.statements != null ) {
node.statements.evaluate(context,this);
}
if( node.expr != null ) {
node.expr.evaluate(context,this);
}
context.indent--;
return null;
}
Value evaluate( Context context, WhileStatementNode node ) throws Exception {
String tag = (node.isLeader ? "*"+node.block+":" : ""+node.block+": ")+"WhileStatement";
emit(context.getIndent()+tag);
context.indent++;
if( node.expr != null ) {
node.expr.evaluate(context,this);
}
if( node.statement != null ) {
node.statement.evaluate(context,this);
}
context.indent--;
return null;
}
Value evaluate( Context context, ForStatementNode node ) throws Exception {
String tag = (node.isLeader ? "*"+node.block+":" : ""+node.block+": ")+"ForStatement";
emit(context.getIndent()+tag);
context.indent++;
if( node.initialize != null ) {
node.initialize.evaluate(context,this);
}
if( node.test != null ) {
node.test.evaluate(context,this);
}
if( node.increment != null ) {
node.increment.evaluate(context,this);
}
if( node.statement != null ) {
node.statement.evaluate(context,this);
}
context.indent--;
return null;
}
Value evaluate( Context context, ForInStatementNode node ) throws Exception {
String tag = (node.isLeader ? "*"+node.block+":" : ""+node.block+": ")+"ForInStatement";
emit(context.getIndent()+tag);
context.indent++;
if( node.property != null ) {
node.property.evaluate(context,this);
}
if( node.object != null ) {
node.object.evaluate(context,this);
}
if( node.statement != null ) {
node.statement.evaluate(context,this);
}
context.indent--;
return null;
}
Value evaluate( Context context, WithStatementNode node ) throws Exception {
String tag = (node.isLeader ? "*"+node.block+":" : ""+node.block+": ")+"WithStatement";
emit(context.getIndent()+tag);
context.indent++;
if( node.expr != null ) {
node.expr.evaluate(context,this);
}
if( node.statement != null ) {
node.statement.evaluate(context,this);
}
context.indent--;
return null;
}
Value evaluate( Context context, ContinueStatementNode node ) throws Exception {
String tag = (node.isLeader ? "*"+node.block+":" : ""+node.block+": ")+"ContinueStatement";
emit(context.getIndent()+tag);
context.indent++;
if( node.expr != null ) {
node.expr.evaluate(context,this);
}
context.indent--;
return null;
}
Value evaluate( Context context, BreakStatementNode node ) throws Exception {
String tag = (node.isLeader ? "*"+node.block+":" : ""+node.block+": ")+"BreakStatement";
emit(context.getIndent()+tag);
context.indent++;
if( node.expr != null ) {
node.expr.evaluate(context,this);
}
context.indent--;
return null;
}
Value evaluate( Context context, ReturnStatementNode node ) throws Exception {
String tag = (node.isLeader ? "*"+node.block+":" : ""+node.block+": ")+"ReturnStatement";
emit(context.getIndent()+tag);
context.indent++;
if( node.expr != null ) {
node.expr.evaluate(context,this);
}
context.indent--;
return null;
}
Value evaluate( Context context, ThrowStatementNode node ) throws Exception {
String tag = (node.isLeader ? "*"+node.block+":" : ""+node.block+": ")+"ThrowStatement";
emit(context.getIndent()+tag);
context.indent++;
if( node.expr != null ) {
node.expr.evaluate(context,this);
}
context.indent--;
return null;
}
Value evaluate( Context context, TryStatementNode node ) throws Exception {
String tag = (node.isLeader ? "*"+node.block+":" : ""+node.block+": ")+"TryStatement";
emit(context.getIndent()+tag);
context.indent++;
if( node.tryblock != null ) {
node.tryblock.evaluate(context,this);
}
if( node.catchlist != null ) {
node.catchlist.evaluate(context,this);
}
if( node.finallyblock != null ) {
node.finallyblock.evaluate(context,this);
}
context.indent--;
return null;
}
Value evaluate( Context context, CatchClauseNode node ) throws Exception {
String tag = (node.isLeader ? "*"+node.block+":" : ""+node.block+": ")+"CatchClause";
emit(context.getIndent()+tag);
context.indent++;
if( node.parameter != null ) {
node.parameter.evaluate(context,this);
}
if( node.statements != null ) {
node.statements.evaluate(context,this);
}
context.indent--;
return null;
}
Value evaluate( Context context, FinallyClauseNode node ) throws Exception {
String tag = (node.isLeader ? "*"+node.block+":" : ""+node.block+": ")+"FinallyClause";
emit(context.getIndent()+tag);
context.indent++;
if( node.statements != null ) {
node.statements.evaluate(context,this);
}
context.indent--;
return null;
}
Value evaluate( Context context, UseStatementNode node ) throws Exception {
String tag = (node.isLeader ? "*"+node.block+":" : ""+node.block+": ")+"UseStatement";
emit(context.getIndent()+tag);
context.indent++;
if( node.expr != null ) {
node.expr.evaluate(context,this);
}
context.indent--;
return null;
}
Value evaluate( Context context, IncludeStatementNode node ) throws Exception {
String tag = (node.isLeader ? "*"+node.block+":" : ""+node.block+": ")+"IncludeStatement";
emit(context.getIndent()+tag);
context.indent++;
if( node.item != null ) {
node.item.evaluate(context,this);
}
context.indent--;
return null;
}
// Definitions
Value evaluate( Context context, ImportDefinitionNode node ) throws Exception {
String tag = "ImportDefinition";
emit(context.getIndent()+tag);
context.indent++;
if( node.item != null ) {
node.item.evaluate(context,this);
}
if( node.list != null ) {
node.list.evaluate(context,this);
}
context.indent--;
return null;
}
Value evaluate( Context context, ImportBindingNode node ) throws Exception {
String tag = "ImportBinding";
emit(context.getIndent()+tag);
context.indent++;
if( node.identifier != null ) {
node.identifier.evaluate(context,this);
}
if( node.item != null ) {
node.item.evaluate(context,this);
}
context.indent--;
return null;
}
Value evaluate( Context context, AnnotatedDefinitionNode node ) throws Exception {
String tag = (node.isLeader ? "*"+node.block+":" : ""+node.block+": ")+"AnnotatedDefinition";
emit(context.getIndent()+tag);
context.indent++;
if( node.attributes != null ) {
node.attributes.evaluate(context,this);
}
if( node.definition != null ) {
node.definition.evaluate(context,this);
}
context.indent--;
return null;
}
Value evaluate( Context context, AttributeListNode node ) throws Exception {
String tag = "AttributeList";
//emit(context.getIndent()+tag);
//context.indent++;
if( node.item != null ) {
node.item.evaluate(context,this);
}
if( node.list != null ) {
node.list.evaluate(context,this);
}
//context.indent--;
return null;
}
Value evaluate( Context context, ExportDefinitionNode node ) throws Exception {
String tag = "ExportDefinition";
emit(context.getIndent()+tag);
context.indent++;
if( node.list != null ) {
node.list.evaluate(context,this);
}
context.indent--;
return null;
}
Value evaluate( Context context, ExportBindingNode node ) throws Exception {
String tag = "ExportBinding";
emit(context.getIndent()+tag);
context.indent++;
if( node.name != null ) {
node.name.evaluate(context,this);
}
if( node.value != null ) {
node.value.evaluate(context,this);
}
context.indent--;
return null;
}
Value evaluate( Context context, VariableDefinitionNode node ) throws Exception {
String tag = "VariableDefinition: " + Token.getTokenClassName(node.kind);
emit(context.getIndent()+tag);
context.indent++;
if( node.list != null ) {
node.list.evaluate(context,this);
}
context.indent--;
return null;
}
Value evaluate( Context context, VariableBindingNode node ) throws Exception {
String tag = "VariableBinding";
emit(context.getIndent()+tag);
context.indent++;
if( node.variable != null ) {
node.variable.evaluate(context,this);
}
if( node.initializer != null ) {
node.initializer.evaluate(context,this);
}
context.indent--;
return null;
}
Value evaluate( Context context, TypedVariableNode node ) throws Exception {
String tag = "TypedVariable";
emit(context.getIndent()+tag);
context.indent++;
if( node.identifier != null ) {
node.identifier.evaluate(context,this);
}
if( node.type != null ) {
node.type.evaluate(context,this);
}
context.indent--;
return null;
}
Value evaluate( Context context, FunctionDefinitionNode node ) throws Exception {
String tag = "FunctionDefinition";
emit(context.getIndent()+tag);
context.indent++;
if( node.decl != null ) {
node.decl.evaluate(context,this);
}
if( node.body != null ) {
node.body.evaluate(context,this);
}
context.indent--;
return null;
}
Value evaluate( Context context, FunctionDeclarationNode node ) throws Exception {
String tag = "FunctionDeclaration";
emit(context.getIndent()+tag);
context.indent++;
if( node.name != null ) {
node.name.evaluate(context,this);
}
if( node.signature != null ) {
node.signature.evaluate(context,this);
}
context.indent--;
return null;
}
Value evaluate( Context context, FunctionSignatureNode node ) throws Exception {
String tag = "FunctionSignature";
emit(context.getIndent()+tag);
context.indent++;
if( node.parameter != null ) {
node.parameter.evaluate(context,this);
}
if( node.result != null ) {
node.result.evaluate(context,this);
}
context.indent--;
return null;
}
Value evaluate( Context context, FunctionNameNode node ) throws Exception {
String tag = "FunctionName: " + ((node.kind==empty_token)?"":Token.getTokenClassName(node.kind));
emit(context.getIndent()+tag);
context.indent++;
if( node.name != null ) {
node.name.evaluate(context,this);
}
context.indent--;
return null;
}
Value evaluate( Context context, ParameterNode node ) throws Exception {
String tag = "Parameter";
emit(context.getIndent()+tag);
context.indent++;
if( node.identifier != null ) {
node.identifier.evaluate(context,this);
}
if( node.type != null ) {
node.type.evaluate(context,this);
}
context.indent--;
return null;
}
Value evaluate( Context context, OptionalParameterNode node ) throws Exception {
String tag = "OptionalParameter";
emit(context.getIndent()+tag);
context.indent++;
if( node.parameter != null ) {
node.parameter.evaluate(context,this);
}
if( node.initializer != null ) {
node.initializer.evaluate(context,this);
}
context.indent--;
return null;
}
Value evaluate( Context context, ClassDefinitionNode node ) throws Exception {
String tag = "ClassDefinition";
emit(context.getIndent()+tag);
context.indent++;
if( node.name != null ) {
node.name.evaluate(context,this);
}
if( node.inheritance != null ) {
node.inheritance.evaluate(context,this);
}
if( node.statements != null ) {
node.statements.evaluate(context,this);
}
context.indent--;
return null;
}
Value evaluate( Context context, InheritanceNode node ) throws Exception {
String tag = "Inheritance";
emit(context.getIndent()+tag);
context.indent++;
if( node.baseclass != null ) {
node.baseclass.evaluate(context,this);
}
if( node.interfaces != null ) {
node.interfaces.evaluate(context,this);
}
context.indent--;
return null;
}
Value evaluate( Context context, ClassDeclarationNode node ) throws Exception {
String tag = "ClassDeclaration";
emit(context.getIndent()+tag);
context.indent++;
if( node.name != null ) {
node.name.evaluate(context,this);
}
context.indent--;
return null;
}
Value evaluate( Context context, NamespaceDefinitionNode node ) throws Exception {
String tag = "NamespaceDefinition";
emit(context.getIndent()+tag);
context.indent++;
if( node.name != null ) {
node.name.evaluate(context,this);
}
if( node.extendslist != null ) {
node.extendslist.evaluate(context,this);
}
context.indent--;
return null;
}
Value evaluate( Context context, PackageDefinitionNode node ) throws Exception {
String tag = "PackageDefinition";
emit(context.getIndent()+tag);
context.indent++;
if( node.name != null ) {
node.name.evaluate(context,this);
}
if( node.statements != null ) {
node.statements.evaluate(context,this);
}
context.indent--;
return null;
}
Value evaluate( Context context, ProgramNode node ) throws Exception {
String tag = "Program";
emit(context.getIndent()+tag);
context.indent++;
node.statements.evaluate(context,this);
context.indent--;
return null;
}
}
/*
* The end.
*/

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,95 @@
/*
* The contents of this file are subject to the Netscape Public
* License Version 1.1 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.mozilla.org/NPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* The Original Code is mozilla.org code.
*
* The Initial Developer of the Original Code is Mountain View Compiler
* Company. Portions created by Mountain View Compiler Company are
* Copyright (C) 1998-2000 Mountain View Compiler Company. All
* Rights Reserved.
*
* Contributor(s):
* Jeff Dyer <jeff@compilercompany.com>
*/
package com.compilercompany.ecmascript;
import java.io.*;
/**
*
* class Debugger
*
**/
public final class Debugger {
public static PrintStream dbg = null;
private static boolean useSystemOut = false;
public static void setOutFile(String filename) {
try {
PrintStream out = new PrintStream( new FileOutputStream( filename ) );
System.setOut( out );
//System.setErr( outfile );
} catch ( Exception e ) {
e.printStackTrace();
}
}
public static void setErrFile(String filename) {
try {
PrintStream err = new PrintStream( new FileOutputStream( filename ) );
//System.setOut( out );
System.setErr( err );
} catch ( Exception e ) {
e.printStackTrace();
}
}
public static void setDbgFile(String filename) {
try {
if( dbg!=null) {
dbg.close();
}
dbg = new PrintStream( new FileOutputStream( filename ) );
//System.setOut( outfile );
//System.setErr( outfile );
} catch ( Exception e ) {
e.printStackTrace();
}
}
public static void trace( String str ) {
try {
if( useSystemOut )
System.out.println( str );
else {
if( dbg == null ) {
dbg = new PrintStream( new FileOutputStream( "debug.out" ) );
//System.setOut( outfile );
//System.setErr( outfile );
}
dbg.println( str );
}
}
catch( SecurityException e ) {
useSystemOut = true;
System.out.println( str );
}
catch( Exception e ) {
e.printStackTrace();
}
}
}
/*
* The end.
*/

View File

@@ -0,0 +1,490 @@
/*
* Filters and buffers characters from a input reader.
*/
package com.compilercompany.es3c.v1;
import java.io.*;
public class InputBuffer implements CharacterClasses {
private static final boolean debug = false;
private static final boolean debug_nextchar = true;
private static final boolean debug_retract = false;
StringBuffer lineA = new StringBuffer();
StringBuffer lineB = new StringBuffer();
StringBuffer curr_line,prev_line;
int curr_line_offset,prev_line_offset;
int lineA_offset, lineB_offset;
private StringBuffer text;
private int[] line_breaks = new int[1000];
Reader in;
PrintStream err;
String origin;
int pos;
int colPos, lnNum=-1; // <0,0> is the position of the first character.
public static PrintStream out;
public static void setOut(String filename) throws Exception {
out = new PrintStream( new FileOutputStream(filename) );
}
public static void main(String[] args) {
test_retract();
test_markandcopy();
test_getLineText();
}
public InputBuffer( Reader in, PrintStream err, String origin ) {
this(in,err,origin,0);
}
public InputBuffer( Reader in, PrintStream err, String origin, int pos ) {
this.in = in;
this.err = err;
this.origin = origin;
this.pos = pos;
this.text = new StringBuffer();
}
/**
* read()
*
* Read the next character from the input reader and store it in a buffer
* of the full text.
*/
private int read() throws Exception {
int c = in.read();
text.append((char)c);
pos++;
return c;
}
/**
* text()
*/
public String source() {
return text.toString();
}
/**
* nextchar() --
*
* The basic function of nextchar() is to fetch the next character,
* in the input array, increment next and return the fetched character.
*
* To simplify the Scanner, this method also does the following:
* 1. normalizes certain special characters to a common character.
* 2. skips unicode format control characters (category Cf).
* 3. keeps track of line breaks, line position and line number.
* 4. treats <cr>+<lf> as a single line terminator.
* 5. returns 0 when the end of input is reached.
*/
public final int nextchar() throws Exception {
int c = -1;
// If the last character was at the end of a line,
// then swap buffers and fill the new one with characters
// from the input reader.
if( curr_line==null || colPos==curr_line.length() ) {
lnNum++;
colPos=0;
// If the current character is a newline, then read
// the next line of input into the other input buffer.
if( curr_line == lineA ) {
if( lineB == null ) {
lineB = new StringBuffer();
lineB_offset = pos;
}
curr_line = lineB; curr_line_offset = lineB_offset;
prev_line = lineA; prev_line_offset = lineA_offset;
lineA = null;
} else {
if( lineA == null ) {
lineA = new StringBuffer();
lineA_offset = pos;
}
curr_line = lineA; curr_line_offset = lineA_offset;
prev_line = lineB; prev_line_offset = lineB_offset;
lineB = null;
}
while(c != '\n' && c != 0) {
c = read();
if( false ) {
Debugger.trace( "c = " + c );
}
// Skip Unicode 3.0 format-control (general category Cf in
// Unicode Character Database) characters.
while(true) {
switch(c) {
case 0x070f: // SYRIAC ABBREVIATION MARK
case 0x180b: // MONGOLIAN FREE VARIATION SELECTOR ONE
case 0x180c: // MONGOLIAN FREE VARIATION SELECTOR TWO
case 0x180d: // MONGOLIAN FREE VARIATION SELECTOR THREE
case 0x180e: // MONGOLIAN VOWEL SEPARATOR
case 0x200c: // ZERO WIDTH NON-JOINER
case 0x200d: // ZERO WIDTH JOINER
case 0x200e: // LEFT-TO-RIGHT MARK
case 0x200f: // RIGHT-TO-LEFT MARK
case 0x202a: // LEFT-TO-RIGHT EMBEDDING
case 0x202b: // RIGHT-TO-LEFT EMBEDDING
case 0x202c: // POP DIRECTIONAL FORMATTING
case 0x202d: // LEFT-TO-RIGHT OVERRIDE
case 0x202e: // RIGHT-TO-LEFT OVERRIDE
case 0x206a: // INHIBIT SYMMETRIC SWAPPING
case 0x206b: // ACTIVATE SYMMETRIC SWAPPING
case 0x206c: // INHIBIT ARABIC FORM SHAPING
case 0x206d: // ACTIVATE ARABIC FORM SHAPING
case 0x206e: // NATIONAL DIGIT SHAPES
case 0x206f: // NOMINAL DIGIT SHAPES
case 0xfeff: // ZERO WIDTH NO-BREAK SPACE
case 0xfff9: // INTERLINEAR ANNOTATION ANCHOR
case 0xfffa: // INTERLINEAR ANNOTATION SEPARATOR
case 0xfffb: // INTERLINEAR ANNOTATION TERMINATOR
c = read();
continue; // skip it.
default:
break;
}
break; // out of while loop.
}
if( c == 0x000a && prev_line.length()!=0 && prev_line.charAt(prev_line.length()-1) == 0x000d ) {
// If this is one of those funny double line terminators,
// Then ignore the second character by reading on.
line_breaks[lnNum] = pos; // adjust if forward.
c = read();
}
// Line terminators.
if( c == 0x000a ||
c == 0x000d ||
c == 0x2028 ||
c == 0x2029 ) {
curr_line.append((char)c);
c = '\n';
line_breaks[lnNum+1] = pos;
// White space
} else if( c == 0x0009 ||
c == 0x000b ||
c == 0x000c ||
c == 0x0020 ||
c == 0x00a0 ||
false /* other cat Zs' */ ) {
c = ' ';
curr_line.append((char)c);
// End of line
} else if( c == -1 ) {
c = 0;
curr_line.append((char)c);
// All other characters.
} else {
// Use c as is.
curr_line.append((char)c);
}
}
}
// Get the next character.
int ln = lnNum;
int col = colPos;
if( curr_line.length() != 0 && curr_line.charAt(colPos) == 0 ) {
c = 0;
colPos++;
} else if( colPos == curr_line.length()-1 ) {
c = '\n';
colPos++;
} else {
c = curr_line.charAt(colPos++);
}
if( out != null ) {
out.println("Ln " + ln + ", Col " + col + ": nextchar " + Integer.toHexString(c) + " = " + (char)c + " @ " + positionOfNext());
}
if( debug || debug_nextchar ) {
Debugger.trace("Ln " + ln + ", Col " + col + ": nextchar " + Integer.toHexString(c) + " = " + (char)c + " @ " + positionOfNext());
}
return c;
}
/**
* test_nextchar() --
* Return an indication of how nextchar() performs
* in various situations, relative to expectations.
*/
boolean test_nextchar() {
return true;
}
/**
* time_nextchar() --
* Return the milliseconds taken to do various ordinary
* tasks with nextchar().
*/
int time_nextchar() {
return 0;
}
/**
* retract
*
* Backup one character position in the input. If at the beginning
* of the line, then swap buffers and point to the last character
* in the other buffer.
*/
public final void retract() throws Exception {
colPos--;
if( colPos<0 ) {
if( curr_line == prev_line ) {
// Can only retract over one line.
throw new Exception("Can only retract past one line at a time.");
} else if( curr_line == lineA ) {
curr_line = lineB = prev_line;
} else {
curr_line = lineA = prev_line;
}
lnNum--;
colPos = curr_line.length()-1;
curr_line_offset = prev_line_offset;
}
if( debug || debug_retract ) {
Debugger.trace("Ln " + lnNum + ", Col " + colPos + ": retract");
}
return;
}
static boolean test_retract() {
Debugger.trace("test_retract");
Reader reader = new StringReader("abc\ndef\nghi");
try {
InputBuffer inbuf = new InputBuffer(reader,System.err,"test");
int c=-1;
for(int i=0;i<9;i++) {
c = inbuf.nextchar();
}
for(int i=0;i<3;i++) {
inbuf.retract();
c = inbuf.nextchar();
inbuf.retract();
}
while(c!=0) {
c = inbuf.nextchar();
}
} catch (Exception x) {
x.printStackTrace();
System.out.println(x);
}
return true;
}
/**
* classOfNext
*/
public byte classOfNext() {
// return the Unicode character class of the current
// character, which is pointed to by 'next-1'.
return CharacterClasses.data[curr_line.charAt(colPos-1)];
}
/**
* positionOfNext
*/
public int positionOfNext() {
return curr_line_offset+colPos-1;
}
/**
* positionOfMark
*/
public int positionOfMark() {
return line_breaks[markLn]+markCol-1;
}
/**
* mark
*/
int markCol;
int markLn;
public int mark() {
markLn = (lnNum==-1)?0:lnNum; // In case nextchar hasn't been called yet.
markCol = colPos;
if( debug ) {
Debugger.trace("Ln " + markLn + ", Col " + markCol + ": mark");
}
return markCol;
}
/**
* copy
*/
public String copy() throws Exception {
StringBuffer buf = new StringBuffer();
if( debug ) {
Debugger.trace("Ln " + lnNum + ", Col " + colPos + ": copy " + buf);
}
if(markLn!=lnNum || markCol>colPos) {
throw new Exception("Internal error: InputBuffer.copy() markLn = " + markLn + ", lnNum = " + lnNum + ", markCol = " +
markCol + ", colPos = " + colPos );
}
for (int i = markCol-1; i < colPos; i++) {
buf.append(curr_line.charAt(i));
}
return buf.toString();
}
static boolean test_markandcopy() {
Debugger.trace("test_copy");
Reader reader = new StringReader("abc\ndef\nghijklmnopqrst\nuvwxyz");
String s;
try {
InputBuffer inbuf = new InputBuffer(reader,System.err,"test");
int c=-1;
int i;
for(i=0;i<10;i++) {
c = inbuf.nextchar();
}
inbuf.mark();
for(;i<13;i++) {
c = inbuf.nextchar();
}
s = inbuf.copy();
if(s.equals("ijk")) {
Debugger.trace("1: passed: " + s);
} else {
Debugger.trace("1: failed: " + s);
}
while(c!=0) {
c = inbuf.nextchar();
}
s = inbuf.copy();
} catch (Exception x) {
s = x.getMessage();
//x.printStackTrace();
}
if(s.equals("Internal error: InputBuffer.copy() markLn = 2, lnNum = 3, markCol = 2, colPos = 6")) {
Debugger.trace("2: passed: " + s);
} else {
Debugger.trace("2: failed: " + s);
}
return true;
}
public String getLineText(int pos) {
int i,len;
for(i = 0; line_breaks[i] <= pos && i <= lnNum; i++)
;
int offset = line_breaks[i-1];
for(len = offset ; (text.charAt(len)!=(char)-1 &&
text.charAt(len)!=0x0a &&
text.charAt(len)!=0x0d &&
text.charAt(len)!=0x2028 &&
text.charAt(len)!=0x2029) ; len++) {
}
return text.toString().substring(offset,len);
}
static boolean test_getLineText() {
Debugger.trace("test_getLineText");
Reader reader = new StringReader("abc\ndef\nghi");
try {
InputBuffer inbuf = new InputBuffer(reader,System.err,"test");
int c=-1;
for(int i=0;i<9;i++) {
c = inbuf.nextchar();
}
for(int i=0;i<3;i++) {
inbuf.retract();
c = inbuf.nextchar();
inbuf.retract();
}
while(c!=0) {
c = inbuf.nextchar();
}
for(int i=0;i<inbuf.text.length()-1;i++) {
Debugger.trace("text @ " + i + " " + inbuf.getLineText(i));
}
} catch (Exception x) {
x.printStackTrace();
System.out.println(x);
}
return true;
}
public int getColPos(int pos) {
//Debugger.trace("pos " + pos);
int i,len;
for(i = 0; line_breaks[i] <= pos && i <= lnNum; i++)
;
int offset = line_breaks[i-1];
//Debugger.trace("offset " + offset);
return pos-offset;
}
public int getLnNum(int pos) {
int i;
for(i = 0; line_breaks[i] <= pos && i <= lnNum; i++)
;
return i-1;
}
}
/*
* The end.
*/

View File

@@ -0,0 +1,109 @@
/*
* The contents of this file are subject to the Netscape Public
* License Version 1.1 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.mozilla.org/NPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* The Original Code is mozilla.org code.
*
* The Initial Developer of the Original Code is Mountain View Compiler
* Company. Portions created by Mountain View Compiler Company are
* Copyright (C) 1998-2000 Mountain View Compiler Company. All
* Rights Reserved.
*
* Contributor(s):
* Jeff Dyer <jeff@compilercompany.com>
*/
package com.compilercompany.ecmascript;
import java.lang.reflect.*;
import sun.tools.javac.*;
import java.io.*;
/**
* class Shell
*/
public final class Shell {
private static boolean debug = true;
static int failureCount = 0;
public static void main( String[] args ) {
try {
int count = args.length;
String encoding = "UTF-8"; // Alternatives include: "UTF-16", "US-ASCII" (7-bit)
if( args[0].equals("-l") ) {
/* run the input text through the scanner */
try {
Debugger.trace("start "+args[count-1]);
FileInputStream in = new FileInputStream( args[count-1] );
InputStreamReader reader = new InputStreamReader( in, "UTF-8" );
FileOutputStream tokfile = new FileOutputStream( args[count-1] + ".inp" );
PrintWriter tokwriter = new PrintWriter( tokfile);
FileOutputStream errfile = new FileOutputStream( args[count-1] + ".err" );
PrintStream errwriter = new PrintStream( errfile );
//char[] temp = new char[0xffff];
//int len = reader.read( temp, 0, temp.length );
//char[] src = new char[len+1];
//System.arraycopy(temp, 0, src, 0, len);
InputBuffer inp = new InputBuffer( reader, errwriter, args[count-1] );
int result;
String follows;
for( int i = 0; (result = inp.nextchar()) != 0; i++ ) {
tokwriter.println( "" + Integer.toHexString(result) + " " + (char)result );
}
tokwriter.close();
Debugger.trace("finish "+args[count-1]);
}
catch( Exception e ) {
e.printStackTrace();
}
}
/*
if( args[0].equals("-g") ) {
try {
FileInputStream srcfile = new FileInputStream( args[count-1] );
InputStreamReader reader = new InputStreamReader( srcfile );
FileOutputStream errfile = new FileOutputStream( args[count-1] + ".err" );
PrintStream errwriter = new PrintStream( errfile );
char[] temp = new char[0x7ffff];
int len = reader.read( temp, 0, temp.length );
char[] src = new char[len+1];
System.arraycopy(temp, 0, src, 0, len);
UnicodeNormalizationFormCReader ucreader = new UnicodeNormalizationFormCReader( src, errwriter, args[count-1] );
UnicodeNormalizationFormCReader.generateCharacterClassesArray(ucreader);
}
catch( Exception e ) {
e.printStackTrace();
}
}
*/
}
catch( Exception e ) {
e.printStackTrace();
}
}
/**
*
**/
}
/*
* The end.
*/

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,90 @@
/*
* The contents of this file are subject to the Netscape Public
* License Version 1.1 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.mozilla.org/NPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* The Original Code is mozilla.org code.
*
* The Initial Developer of the Original Code is Mountain View Compiler
* Company. Portions created by Mountain View Compiler Company are
* Copyright (C) 1998-2000 Mountain View Compiler Company. All
* Rights Reserved.
*
* Contributor(s):
* Jeff Dyer <jeff@compilercompany.com>
*/
package com.compilercompany.ecmascript;
import java.lang.reflect.*;
import sun.tools.javac.*;
import java.io.*;
/**
* class Shell
*/
public final class Shell implements Tokens {
private static boolean debug = false;
static int failureCount = 0;
public static void main( String[] args ) {
try {
int count = args.length;
if( args[0].equals("-l") ) {
/* run the input text through the scanner */
try {
FileInputStream srcfile = new FileInputStream( args[count-1] );
InputStreamReader reader = new InputStreamReader( srcfile );
FileOutputStream tokfile = new FileOutputStream( args[count-1] + ".tok" );
PrintWriter tokwriter = new PrintWriter( tokfile);
FileOutputStream errfile = new FileOutputStream( args[count-1] + ".err" );
PrintStream errwriter = new PrintStream( errfile );
Scanner scanner = new Scanner( reader, errwriter, args[count-1] );
int result;
String follows;
for( int i = 0; (result = scanner.nexttoken()) != eos_token; i++ ) {
follows = scanner.followsLineTerminator() ? "*" : "";
tokwriter.print( scanner.getPersistentTokenText(result) + follows + " " );
}
tokwriter.close();
/*
for( int i = 0; (result = scanner.nexttoken()) != eos_token; i++ ) {
System.out.println( scanner.lexeme() + "\t\t\t"
+ Token.getTokenClassName(scanner.getTokenClass(result))
+ " (" + result + ")"
+ ": " + scanner.lexeme() );
}
*/
}
catch( Exception e ) {
e.printStackTrace();
}
}
}
catch( Exception e ) {
e.printStackTrace();
}
}
/**
*
**/
}
/*
* The end.
*/

View File

@@ -0,0 +1,397 @@
package com.compilercompany.es3c.v1;
/*
* The states of the scanner.
*/
interface States {
/**
**/
public static final int start_state = 0;
public static final int error_state = start_state-1;
public static final int minusminus_state = start_state+1;
public static final int minusequal_state = minusminus_state +1;
public static final int minus_state = minusequal_state +1;
public static final int notequal_state = minus_state +1;
public static final int not_state = notequal_state +1;
public static final int remainderequal_state = not_state +1;
public static final int remainder_state = remainderequal_state +1;
public static final int logicaland_state = remainder_state +1;
public static final int logicalandassign_state = logicaland_state +1;
public static final int andequal_state = logicalandassign_state +1;
public static final int and_state = andequal_state +1;
public static final int leftparen_state = and_state +1;
public static final int rightparen_state = leftparen_state +1;
public static final int starequal_state = rightparen_state +1;
public static final int star_state = starequal_state +1;
public static final int comma_state = star_state +1;
public static final int dot_state = comma_state +1;
public static final int doubledot_state = dot_state +1;
public static final int tripledot_state = doubledot_state +1;
public static final int slashequal_state = tripledot_state +1;
public static final int slash_state = slashequal_state +1;
public static final int colon_state = slash_state +1;
public static final int doublecolon_state = colon_state+1;
public static final int semicolon_state = doublecolon_state+1;
public static final int questionmark_state = semicolon_state +1;
public static final int leftbracket_state = questionmark_state +1;
public static final int rightbracket_state = leftbracket_state +1;
public static final int bitwisexorassign_state = rightbracket_state +1;
public static final int bitwisexor_state = bitwisexorassign_state+1;
public static final int logicalxor_state = bitwisexor_state+1;
public static final int logicalxorassign_state = logicalxor_state+1;
public static final int leftbrace_state = logicalxorassign_state+1;
public static final int logicalor_state = leftbrace_state+1;
public static final int logicalorassign_state = logicalor_state+1;
public static final int orequal_state = logicalorassign_state +1;
public static final int or_state = orequal_state +1;
public static final int rightbrace_state = or_state +1;
public static final int squiggle_state = rightbrace_state +1;
public static final int plusplus_state = squiggle_state +1;
public static final int plusequal_state = plusplus_state +1;
public static final int plus_state = plusequal_state +1;
public static final int leftshiftequal_state = plus_state +1;
public static final int leftshift_state = leftshiftequal_state +1;
public static final int lessthanorequal_state = leftshift_state +1;
public static final int lessthan_state = lessthanorequal_state +1;
public static final int equal_state = lessthan_state +1;
public static final int equalequal_state = equal_state +1;
public static final int greaterthanorequal_state = equalequal_state +1;
public static final int rightshiftequal_state = greaterthanorequal_state +1;
public static final int unsignedrightshift_state = rightshiftequal_state +1;
public static final int unsignedrightshiftequal_state = unsignedrightshift_state +1;
public static final int rightshift_state = unsignedrightshiftequal_state+1;
public static final int greaterthan_state = rightshift_state +1;
public static final int A_state = greaterthan_state +1;
public static final int N_state = A_state +1;
public static final int AA_state = N_state +1;
public static final int AN_state = AA_state +1;
public static final int singlequote_state = AN_state +1;
public static final int doublequote_state = singlequote_state +1;
public static final int zero_state = doublequote_state +1;
public static final int decimalinteger_state = zero_state +1;
public static final int decimal_state = decimalinteger_state +1;
public static final int exponent_state = decimal_state +1;
public static final int hexinteger_state = exponent_state +1;
public static final int octalinteger_state = hexinteger_state +1;
public static final int slashregexp_state = octalinteger_state +1;
public static final int slashdiv_state = slashregexp_state +1;
public static final int regexp_state = slashdiv_state +1;
public static final int regexpg_state = regexp_state +1;
public static final int regexpi_state = regexpg_state +1;
public static final int regexpm_state = regexpi_state +1;
public static final int regexpgi_state = regexpm_state +1;
public static final int regexpgm_state = regexpgi_state +1;
public static final int regexpim_state = regexpgm_state +1;
public static final int regexpgim_state = regexpim_state +1;
public static final int pound_state = regexpgim_state +1;
public static final int ampersand_state = pound_state +1;
public static final int arrow_state = ampersand_state +1;
public static final int a_state = arrow_state+1;
public static final int ab_state = a_state+1;
public static final int abs_state = ab_state+1;
public static final int abst_state = abs_state+1;
public static final int abstr_state = abst_state+1;
public static final int abstra_state = abstr_state+1;
public static final int abstrac_state = abstra_state+1;
public static final int abstract_state = abstrac_state+1;
public static final int at_state = abstract_state +1;
public static final int att_state = at_state+1;
public static final int attr_state = att_state+1;
public static final int attri_state = attr_state+1;
public static final int attrib_state = attri_state+1;
public static final int attribu_state = attrib_state+1;
public static final int attribut_state = attribu_state+1;
public static final int attribute_state = attribut_state+1;
public static final int b_state = attribute_state+1;
public static final int bo_state = b_state+1;
public static final int boo_state = bo_state+1;
public static final int bool_state = boo_state+1;
public static final int boole_state = bool_state+1;
public static final int boolea_state = boole_state+1;
public static final int boolean_state = boolea_state+1;
public static final int br_state = boolean_state+1;
public static final int bre_state = br_state+1;
public static final int brea_state = bre_state+1;
public static final int break_state = brea_state+1;
public static final int by_state = break_state+1;
public static final int byt_state = by_state+1;
public static final int byte_state = byt_state+1;
public static final int c_state = byte_state+1;
public static final int ca_state = c_state+1;
public static final int cas_state = ca_state+1;
public static final int case_state = cas_state+1;
public static final int cat_state = case_state+1;
public static final int catc_state = cat_state+1;
public static final int catch_state = catc_state+1;
public static final int ch_state = catch_state+1;
public static final int cha_state = ch_state+1;
public static final int char_state = cha_state+1;
public static final int cl_state = char_state+1;
public static final int cla_state = cl_state+1;
public static final int clas_state = cla_state+1;
public static final int class_state = clas_state+1;
public static final int co_state = class_state+1;
public static final int con_state = co_state+1;
public static final int cont_state = con_state+1;
public static final int conti_state = cont_state+1;
public static final int contin_state = conti_state+1;
public static final int continu_state = contin_state+1;
public static final int continue_state = continu_state+1;
public static final int cons_state = continue_state+1;
public static final int const_state = cons_state+1;
public static final int constr_state = const_state+1;
public static final int constru_state = constr_state+1;
public static final int construc_state = constru_state+1;
public static final int construct_state = construc_state+1;
public static final int constructo_state = construct_state+1;
public static final int constructor_state = constructo_state+1;
public static final int d_state = constructor_state+1;
public static final int de_state = d_state+1;
public static final int deb_state = de_state+1;
public static final int debu_state = deb_state+1;
public static final int debug_state = debu_state+1;
public static final int debugg_state = debug_state+1;
public static final int debugge_state = debugg_state+1;
public static final int debugger_state = debugge_state+1;
public static final int def_state = debugger_state+1;
public static final int defa_state = def_state+1;
public static final int defau_state = defa_state+1;
public static final int defaul_state = defau_state+1;
public static final int default_state = defaul_state+1;
public static final int del_state = default_state+1;
public static final int dele_state = del_state+1;
public static final int delet_state = dele_state+1;
public static final int delete_state = delet_state+1;
public static final int do_state = delete_state+1;
public static final int dou_state = do_state+1;
public static final int doub_state = dou_state+1;
public static final int doubl_state = doub_state+1;
public static final int double_state = doubl_state+1;
public static final int e_state = double_state+1;
public static final int el_state = e_state+1;
public static final int els_state = el_state+1;
public static final int else_state = els_state+1;
public static final int en_state = else_state+1;
public static final int enu_state = en_state+1;
public static final int enum_state = enu_state+1;
public static final int ev_state = enum_state+1;
public static final int eva_state = ev_state+1;
public static final int eval_state = eva_state+1;
public static final int ex_state = eval_state+1;
public static final int exp_state = ex_state+1;
public static final int expo_state = exp_state+1;
public static final int expor_state = expo_state+1;
public static final int export_state = expor_state+1;
public static final int ext_state = export_state+1;
public static final int exte_state = ext_state+1;
public static final int exten_state = exte_state+1;
public static final int extend_state = exten_state+1;
public static final int extends_state = extend_state+1;
public static final int f_state = extends_state+1;
public static final int fa_state = f_state+1;
public static final int fal_state = fa_state+1;
public static final int fals_state = fal_state+1;
public static final int false_state = fals_state+1;
public static final int fi_state = false_state+1;
public static final int fin_state = fi_state+1;
public static final int fina_state = fin_state+1;
public static final int final_state = fina_state+1;
public static final int finall_state = final_state+1;
public static final int finally_state = finall_state+1;
public static final int fl_state = finally_state+1;
public static final int flo_state = fl_state+1;
public static final int floa_state = flo_state+1;
public static final int float_state = floa_state+1;
public static final int fo_state = float_state+1;
public static final int for_state = fo_state+1;
public static final int fu_state = for_state+1;
public static final int fun_state = fu_state+1;
public static final int func_state = fun_state+1;
public static final int funct_state = func_state+1;
public static final int functi_state = funct_state+1;
public static final int functio_state = functi_state+1;
public static final int function_state = functio_state+1;
public static final int g_state = function_state+1;
public static final int go_state = g_state+1;
public static final int got_state = go_state+1;
public static final int goto_state = got_state+1;
public static final int i_state = goto_state+1;
public static final int if_state = i_state+1;
public static final int im_state = if_state+1;
public static final int imp_state = im_state+1;
public static final int impl_state = imp_state+1;
public static final int imple_state = impl_state+1;
public static final int implem_state = imple_state+1;
public static final int impleme_state = implem_state+1;
public static final int implemen_state = impleme_state+1;
public static final int implement_state = implemen_state+1;
public static final int implements_state = implement_state+1;
public static final int impo_state = implements_state+1;
public static final int impor_state = impo_state+1;
public static final int import_state = impor_state+1;
public static final int in_state = import_state+1;
public static final int inc_state = in_state+1;
public static final int incl_state = inc_state+1;
public static final int inclu_state = incl_state+1;
public static final int includ_state = inclu_state+1;
public static final int include_state = includ_state+1;
public static final int ins_state = include_state+1;
public static final int inst_state = ins_state+1;
public static final int insta_state = inst_state+1;
public static final int instan_state = insta_state+1;
public static final int instanc_state = instan_state+1;
public static final int instance_state = instanc_state+1;
public static final int instanceo_state = instance_state+1;
public static final int instanceof_state = instanceo_state+1;
public static final int int_state = instanceof_state+1;
public static final int inte_state = int_state+1;
public static final int inter_state = inte_state+1;
public static final int interf_state = inter_state+1;
public static final int interfa_state = interf_state+1;
public static final int interfac_state = interfa_state+1;
public static final int interface_state = interfac_state+1;
public static final int l_state = interface_state+1;
public static final int lo_state = l_state+1;
public static final int lon_state = lo_state+1;
public static final int long_state = lon_state+1;
public static final int n_state = long_state+1;
public static final int na_state = n_state+1;
public static final int nam_state = na_state+1;
public static final int name_state = nam_state+1;
public static final int names_state = name_state+1;
public static final int namesp_state = names_state+1;
public static final int namespa_state = namesp_state+1;
public static final int namespac_state = namespa_state+1;
public static final int namespace_state = namespac_state+1;
public static final int nat_state = namespace_state+1;
public static final int nati_state = nat_state+1;
public static final int nativ_state = nati_state+1;
public static final int native_state = nativ_state+1;
public static final int ne_state = native_state+1;
public static final int new_state = ne_state+1;
public static final int nu_state = new_state+1;
public static final int nul_state = nu_state+1;
public static final int null_state = nul_state+1;
public static final int r_state = null_state+1;
public static final int re_state = r_state+1;
public static final int ret_state = re_state+1;
public static final int retu_state = ret_state+1;
public static final int retur_state = retu_state+1;
public static final int return_state = retur_state +1;
public static final int p_state = return_state +1;
public static final int pa_state = p_state +1;
public static final int pac_state = pa_state +1;
public static final int pack_state = pac_state +1;
public static final int packa_state = pack_state +1;
public static final int packag_state = packa_state +1;
public static final int package_state = packag_state +1;
public static final int pr_state = package_state +1;
public static final int pri_state = pr_state +1;
public static final int priv_state = pri_state +1;
public static final int priva_state = priv_state +1;
public static final int privat_state = priva_state +1;
public static final int private_state = privat_state +1;
public static final int pro_state = private_state +1;
public static final int prot_state = pro_state +1;
public static final int prote_state = prot_state +1;
public static final int protec_state = prote_state +1;
public static final int protect_state = protec_state +1;
public static final int protecte_state = protect_state +1;
public static final int protected_state = protecte_state +1;
public static final int pu_state = protected_state +1;
public static final int pub_state = pu_state +1;
public static final int publ_state = pub_state +1;
public static final int publi_state = publ_state +1;
public static final int public_state = publi_state +1;
public static final int s_state = public_state +1;
public static final int sh_state = s_state +1;
public static final int sho_state = sh_state +1;
public static final int shor_state = sho_state +1;
public static final int short_state = shor_state +1;
public static final int st_state = short_state +1;
public static final int sta_state = st_state +1;
public static final int stat_state = sta_state +1;
public static final int stati_state = stat_state +1;
public static final int static_state = stati_state +1;
public static final int su_state = static_state +1;
public static final int sup_state = su_state +1;
public static final int supe_state = sup_state +1;
public static final int super_state = supe_state +1;
public static final int sw_state = super_state +1;
public static final int swi_state = sw_state +1;
public static final int swit_state = swi_state +1;
public static final int switc_state = swit_state +1;
public static final int switch_state = switc_state +1;
public static final int sy_state = switch_state +1;
public static final int syn_state = sy_state +1;
public static final int sync_state = syn_state +1;
public static final int synch_state = sync_state +1;
public static final int synchr_state = synch_state +1;
public static final int synchro_state = synchr_state +1;
public static final int synchron_state = synchro_state +1;
public static final int synchroni_state = synchron_state +1;
public static final int synchroniz_state = synchroni_state +1;
public static final int synchronize_state = synchroniz_state +1;
public static final int synchronized_state = synchronize_state +1;
public static final int t_state = synchronized_state+1;
public static final int th_state = t_state +1;
public static final int thi_state = th_state +1;
public static final int this_state = thi_state +1;
public static final int thr_state = this_state +1;
public static final int thro_state = thr_state +1;
public static final int throw_state = thro_state +1;
public static final int throws_state = throw_state +1;
public static final int tr_state = throws_state +1;
public static final int tra_state = tr_state +1;
public static final int tran_state = tra_state +1;
public static final int trans_state = tran_state +1;
public static final int transi_state = trans_state +1;
public static final int transie_state = transi_state +1;
public static final int transien_state = transie_state +1;
public static final int transient_state = transien_state +1;
public static final int tru_state = transient_state +1;
public static final int true_state = tru_state +1;
public static final int try_state = true_state +1;
public static final int ty_state = try_state +1;
public static final int typ_state = ty_state +1;
public static final int type_state = typ_state +1;
public static final int typeo_state = type_state +1;
public static final int typeof_state = typeo_state +1;
public static final int u_state = typeof_state +1;
public static final int us_state = u_state+1;
public static final int use_state = us_state+1;
public static final int v_state = use_state+1;
public static final int va_state = v_state +1;
public static final int var_state = va_state +1;
public static final int vo_state = var_state +1;
public static final int vol_state = vo_state +1;
public static final int vola_state = vol_state +1;
public static final int volat_state = vola_state +1;
public static final int volati_state = volat_state +1;
public static final int volatil_state = volati_state +1;
public static final int volatile_state = volatil_state +1;
public static final int voi_state = volatile_state +1;
public static final int void_state = voi_state +1;
public static final int w_state = void_state +1;
public static final int wh_state = w_state +1;
public static final int whi_state = wh_state +1;
public static final int whil_state = whi_state +1;
public static final int while_state = whil_state +1;
public static final int wi_state = while_state +1;
public static final int wit_state = wi_state +1;
public static final int with_state = wit_state +1;
public static final int blockcomment_state = with_state+1;
public static final int blockcommentstar_state = blockcomment_state+1;
public static final int linecomment_state = blockcommentstar_state+1;
public static final int eol_state = linecomment_state+1;
}
/*
* The end.
*/

View File

@@ -0,0 +1,61 @@
package com.compilercompany.es3c.v1;
/**
* Represents token instances: literals and identifiers.
*
* This file implements the class Token that is used to carry
* information from the Scanner to the Parser.
*/
import java.util.Vector;
public final class Token implements Tokens {
int tokenClass;
String lexeme;
public Token( int tokenClass, String lexeme ) {
this.tokenClass = tokenClass;
this.lexeme = lexeme;
}
public final int getTokenClass() {
return tokenClass;
}
public final String getTokenText() {
if( tokenClass == stringliteral_token ) {
// erase quotes.
return lexeme.substring(1,lexeme.length()-1);
}
return lexeme;
}
public final String getTokenSource() {
return lexeme;
}
public static String getTokenClassName( int token_class ) {
return tokenClassNames[-1*token_class];
}
/**
* main()
*
* Unit test driver. Execute the command 'java Token' at the
* shell to verify this class' basic functionality.
*/
public static void main(String[] args) {
System.out.println("Token begin");
for(int i = 0; i>=stringliteral_token;i--) {
System.out.println(tokenClassNames[-1*i]);
}
System.out.println("Token end");
}
}
/*
* The end.
*/

View File

@@ -0,0 +1,303 @@
package com.compilercompany.es3c.v1;
/*
* Defines token classes and their print names.
*
* This interface defines values for each token class that occurs in
* ECMAScript 4. All but numericliteral, stringliteral, regexpliteral, and
* identifier are singleton and therefore a fully described by their
* token class defined here. The other four however can have an infinite number
* of instances each with a unique identifier and associated instance
* data. We use positive identifiers to signify instances of these
* token classes so that the instance data can be stored in an array,
* or set of arrays with the token value specifying its index.
*/
public interface Tokens {
/**
* Token class values are negative, and token instances are positive so
* that their values can point to their instance data in an array.
*/
public static final int first_token = -1;
public static final int eos_token = first_token-0;
public static final int minus_token = first_token - 1;
public static final int minusminus_token = minus_token - 1;
public static final int not_token = minusminus_token - 1;
public static final int notequals_token = not_token - 1;
public static final int strictnotequals_token = notequals_token - 1;
public static final int pound_token = strictnotequals_token - 1;
public static final int modulus_token = pound_token - 1;
public static final int modulusassign_token = modulus_token - 1;
public static final int bitwiseand_token = modulusassign_token - 1;
public static final int logicaland_token = bitwiseand_token - 1;
public static final int logicalandassign_token = logicaland_token - 1;
public static final int bitwiseandassign_token = logicalandassign_token - 1;
public static final int leftparen_token = bitwiseandassign_token - 1;
public static final int rightparen_token = leftparen_token - 1;
public static final int mult_token = rightparen_token - 1;
public static final int multassign_token = mult_token - 1;
public static final int comma_token = multassign_token - 1;
public static final int dot_token = comma_token - 1;
public static final int doubledot_token = dot_token - 1;
public static final int tripledot_token = doubledot_token - 1;
public static final int div_token = tripledot_token - 1;
public static final int divassign_token = div_token - 1;
public static final int colon_token = divassign_token - 1;
public static final int doublecolon_token = colon_token - 1;
public static final int semicolon_token = doublecolon_token - 1;
public static final int questionmark_token = semicolon_token - 1;
public static final int ampersand_token = questionmark_token - 1;
public static final int leftbracket_token = ampersand_token - 1;
public static final int rightbracket_token = leftbracket_token - 1 ;
public static final int bitwisexor_token = rightbracket_token - 1;
public static final int logicalxor_token = bitwisexor_token - 1;
public static final int logicalxorassign_token = logicalxor_token - 1;
public static final int bitwisexorassign_token = logicalxorassign_token - 1;
public static final int leftbrace_token = bitwisexorassign_token - 1;
public static final int bitwiseor_token = leftbrace_token - 1;
public static final int logicalor_token = bitwiseor_token - 1;
public static final int logicalorassign_token = logicalor_token - 1;
public static final int bitwiseorassign_token = logicalorassign_token - 1;
public static final int rightbrace_token = bitwiseorassign_token - 1;
public static final int bitwisenot_token = rightbrace_token - 1;
public static final int plus_token = bitwisenot_token - 1;
public static final int plusplus_token = plus_token - 1;
public static final int plusassign_token = plusplus_token - 1;
public static final int lessthan_token = plusassign_token - 1;
public static final int leftshift_token = lessthan_token - 1;
public static final int leftshiftassign_token = leftshift_token - 1;
public static final int lessthanorequals_token = leftshiftassign_token - 1;
public static final int assign_token = lessthanorequals_token - 1;
public static final int minusassign_token = assign_token - 1;
public static final int equals_token = minusassign_token - 1;
public static final int strictequals_token = equals_token - 1;
public static final int greaterthan_token = strictequals_token - 1;
public static final int arrow_token = greaterthan_token - 1;
public static final int greaterthanorequals_token = arrow_token - 1;
public static final int rightshift_token = greaterthanorequals_token - 1;
public static final int rightshiftassign_token = rightshift_token - 1;
public static final int unsignedrightshift_token = rightshiftassign_token - 1;
public static final int unsignedrightshiftassign_token = unsignedrightshift_token - 1;
public static final int abstract_token = unsignedrightshiftassign_token - 1;
public static final int attribute_token = abstract_token - 1;
public static final int boolean_token = attribute_token - 1;
public static final int break_token = boolean_token - 1;
public static final int byte_token = break_token - 1;
public static final int case_token = byte_token - 1;
public static final int catch_token = case_token - 1;
public static final int char_token = catch_token - 1;
public static final int class_token = char_token - 1;
public static final int const_token = class_token - 1;
public static final int constructor_token = const_token - 1;
public static final int continue_token = constructor_token - 1;
public static final int debugger_token = continue_token - 1;
public static final int default_token = debugger_token - 1;
public static final int delete_token = default_token - 1;
public static final int do_token = delete_token - 1;
public static final int double_token = do_token - 1;
public static final int else_token = double_token - 1;
public static final int enum_token = else_token - 1;
public static final int eval_token = enum_token - 1;
public static final int export_token = eval_token - 1;
public static final int extends_token = export_token - 1;
public static final int false_token = extends_token - 1;
public static final int final_token = false_token - 1;
public static final int finally_token = final_token - 1;
public static final int float_token = finally_token - 1;
public static final int for_token = float_token - 1;
public static final int function_token = for_token - 1;
public static final int get_token = function_token - 1;
public static final int goto_token = get_token - 1;
public static final int if_token = goto_token - 1;
public static final int implements_token = if_token - 1;
public static final int import_token = implements_token - 1;
public static final int in_token = import_token - 1;
public static final int include_token = in_token - 1;
public static final int instanceof_token = include_token - 1;
public static final int int_token = instanceof_token - 1;
public static final int interface_token = int_token - 1;
public static final int long_token = interface_token - 1;
public static final int namespace_token = long_token - 1;
public static final int native_token = namespace_token - 1;
public static final int new_token = native_token - 1;
public static final int null_token = new_token - 1;
public static final int package_token = null_token - 1;
public static final int private_token = package_token - 1;
public static final int protected_token = private_token - 1;
public static final int public_token = protected_token - 1;
public static final int return_token = public_token - 1;
public static final int set_token = return_token - 1;
public static final int short_token = set_token - 1;
public static final int static_token = short_token - 1;
public static final int super_token = static_token - 1;
public static final int switch_token = super_token - 1;
public static final int synchronized_token = switch_token - 1;
public static final int this_token = synchronized_token - 1;
public static final int throw_token = this_token - 1;
public static final int throws_token = throw_token - 1;
public static final int transient_token = throws_token - 1;
public static final int true_token = transient_token - 1;
public static final int try_token = true_token - 1;
public static final int typeof_token = try_token - 1;
public static final int use_token = typeof_token - 1;
public static final int var_token = use_token - 1;
public static final int void_token = var_token - 1;
public static final int volatile_token = void_token - 1;
public static final int while_token = volatile_token - 1;
public static final int with_token = while_token - 1;
public static final int identifier_token = with_token - 1;
public static final int numberliteral_token = identifier_token - 1;
public static final int regexpliteral_token = numberliteral_token - 1;
public static final int stringliteral_token = regexpliteral_token - 1;
public static final int eol_token = stringliteral_token - 1;
public static final int empty_token = eol_token - 1;
public static final int error_token = empty_token - 1;
public static final int last_token = empty_token - 1;
public static final String[] tokenClassNames = {
"<unused index>",
"<eos>",
"minus_token",
"minusminus_token",
"not_token",
"notequals_token",
"strictnotequals_token",
"pound_token",
"modulus_token",
"modulusassign_token",
"bitwiseand_token",
"logicaland_token",
"logicalandassign_token",
"bitwiseandassign_token",
"leftparen_token",
"rightparen_token",
"mult_token",
"multassign_token",
"comma_token",
"dot_token",
"doubledot_token",
"tripledot_token",
"div_token",
"divassign_token",
"colon_token",
"doublecolon_token",
"semicolon_token",
"questionmark_token",
"ampersand_token",
"leftbracket_token",
"rightbracket_token",
"bitwisexor_token",
"logicalxor_token",
"logicalxorassign_token",
"bitwisexorassign_token",
"leftbrace_token",
"bitwiseor_token",
"logicalor_token",
"logicalorassign_token",
"bitwiseorassign_token",
"rightbrace_token",
"bitwisenot_token",
"plus_token",
"plusplus_token",
"plusassign_token",
"lessthan_token",
"leftshift_token",
"leftshiftassign_token",
"lessthanorequals_token",
"assign_token",
"minusassign_token",
"equals_token",
"strictequals_token",
"greaterthan_token",
"arrow_token",
"greaterthanorequals_token",
"rightshift_token",
"rightshiftassign_token",
"unsignedrightshift_token",
"unsignedrightshiftassign_token",
"abstract_token",
"attribute_token",
"boolean_token",
"break_token",
"byte_token",
"case_token",
"catch_token",
"char_token",
"class_token",
"const_token",
"constructor_token",
"continue_token",
"debugger_token",
"default_token",
"delete_token",
"do_token",
"double_token",
"else_token",
"enum_token",
"eval_token",
"export_token",
"extends_token",
"false_token",
"final_token",
"finally_token",
"float_token",
"for_token",
"function_token",
"get_token",
"goto_token",
"if_token",
"implements_token",
"import_token",
"in_token",
"include_token",
"instanceof_token",
"int_token",
"interface_token",
"long_token",
"namespace_token",
"native_token",
"new_token",
"null_token",
"package_token",
"private_token",
"protected_token",
"public_token",
"return_token",
"set_token",
"short_token",
"static_token",
"super_token",
"switch_token",
"synchronized_token",
"this_token",
"throw_token",
"throws_token",
"transient_token",
"true_token",
"try_token",
"typeof_token",
"use_token",
"var_token",
"void_token",
"volatile_token",
"while_token",
"with_token",
"identifier_token",
"numberliteral_token",
"regexpliteral_token",
"stringliteral_token",
"<eol>",
"<empty>",
"<error>"
};
}
/*
* The end.
*/

View File

@@ -0,0 +1,186 @@
import com.compilercompany.es3c.v1.*;
import java.io.*;
/*
* The main driver.
*/
public class Main {
String[] classes;
/**
* Entry point.
*/
public static void main(String[] args) {
new Main(args).run();
System.exit(0);
}
/**
* Parse options.
*/
private static boolean traceInput = false;
private static boolean traceLexer = false;
private static boolean traceParser = false;
private static boolean doASM = false;
private static boolean debug = false;
public Main(String[] args) {
if (args.length == 0) {
System.out.println("Wrong args, read the 'readme' and try again");
}
/* Default values for options, overridden by user options. */
int i = 0;
for (; i < args.length; i++) {
if (args[i].equals("-i")||args[i].equals("-input")) {
traceInput = true;
} else if (args[i].equals("-l")||args[i].equals("-lexer")) {
traceLexer = true;
} else if (args[i].equals("-p")||args[i].equals("-parser")) {
traceParser = true;
} else if (args[i].equals("-d")||args[i].equals("-debug")) {
debug = true;
} else if (args[i].equals("-a")||args[i].equals("-asm")) {
doASM = true;
} else if (args[i].charAt(0) == '-') {
System.out.println("Unknown.option "+ args[i]);
} else {
break; /* The rest must be classes. */
}
}
/*
* Grab the rest of argv[] ... this must be the classes.
*/
classes = new String[args.length - i];
System.arraycopy(args, i, classes, 0, args.length - i);
if (classes.length == 0) {
System.out.println("No script specified");
}
}
public void run() {
try {
compile("",classes);
} catch (Exception x) {
x.printStackTrace();
}
}
static final void compile(String name, String[] input) throws Exception {
Debugger.trace( "begin testEvaluator: " + name );
String result;
Node node;
Value type;
Evaluator evaluator;
Value value = UndefinedValue.undefinedValue;
Class pc = Parser.class;
Class[] args = new Class[0];
Parser parser;
long t=0;
ObjectValue global = null;
int errorCount=0;
for( int i = 0; i < input.length; i++ ) {
try {
String scriptfile = input[i].substring(0,input[i].lastIndexOf('.'));
String scriptname = scriptfile.substring(scriptfile.lastIndexOf('/')+1,scriptfile.length());
if( traceInput ) {
InputBuffer.setOut(input[i]+".inp");
} if( traceLexer ) {
Scanner.setOut(input[i]+".lex");
} if( debug ) {
Debugger.setDbgFile( input[i]+".dbg" );
}
Debugger.setErrFile( input[i]+".err" );
FileInputStream srcfile = new FileInputStream( input[i] );
InputStreamReader reader = new InputStreamReader( srcfile );
Context context = new Context();
global = new ObjectValue("__systemGlobal", new GlobalObject());
context.pushScope(global);
parser = new Parser(reader);
Evaluator cevaluator = new ConstantEvaluator();
t = System.currentTimeMillis();
node = parser.parseProgram();
errorCount = parser.errorCount();
if( errorCount == 0 ) {
if( traceParser ) {
Debugger.trace("setting parser output to " + input[i]);
JSILGenerator.setOut( input[i]+".par" );
node.evaluate(context,new JSILGenerator());
}
//Evaluator evaluator;
context.setEvaluator(new BlockEvaluator());
node.evaluate(context, context.getEvaluator());
//JSILGenerator.setOut( input[i]+".blocks" );
//context.setEvaluator(new JSILGenerator(false));
//node.evaluate(context, context.getEvaluator());
context.setEvaluator(new ConstantEvaluator());
value = node.evaluate(context, context.getEvaluator());
context.setEvaluator(new JSILGenerator());
JSILGenerator.setOut( input[i]+".jsil" );
node.evaluate(context, context.getEvaluator());
errorCount = context.errorCount();
ClassFileGenerator generator = new ClassFileGenerator();
generator.init(scriptname);
context.setEvaluator(generator);
node.evaluate(context,generator);
FileOutputStream out = new FileOutputStream(scriptfile+".class");
out.write(generator.getBytes());
out.close();
}
t = System.currentTimeMillis() - t;
//Debugger.trace(""+global);
System.out.println(input[i] + ": "+ errorCount +" errors [" + Long.toString(t) + " msec]" );
} catch( Exception x ) {
x.printStackTrace();
t = System.currentTimeMillis() - t;
System.out.println(input[i] + ": internal error" );
}
//Debugger.trace( " " + i + " passed in " + Long.toString(t) +
// " msec: [" + input[i] + "] = " + result );
}
}
}
/*
* The end.
*/

View File

@@ -0,0 +1,179 @@
/*
* The contents of this file are subject to the Netscape Public
* License Version 1.1 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.mozilla.org/NPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* The Original Code is mozilla.org code.
*
* The Initial Developer of the Original Code is Mountain View Compiler
* Company. Portions created by Mountain View Compiler Company are
* Copyright (C) 1998-2000 Mountain View Compiler Company. All
* Rights Reserved.
*
* Contributor(s):
* Jeff Dyer <jeff@compilercompany.com>
*/
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ResourceBundle;
import java.text.MessageFormat;
import java.util.MissingResourceException;
/**
* Messages, verbose and error handling support.
*
* For errors, the failure modes are:
* error -- User did something wrong
* bug -- Bug has occurred in javah
* fatal -- We can't even find resources, so bail fast, don't localize
*
* @version 1.6, 02/02/00
*/
public class Util {
/*
* Help for verbosity.
*/
public static boolean verbose = false;
public static void log(String s) {
System.out.println(s);
}
/*
* Help for loading localized messages.
*/
private static ResourceBundle m;
private static void initMessages() {
try {
m=ResourceBundle.getBundle("com.sun.tools.javah.resources.l10n");
} catch (MissingResourceException mre) {
fatal("Error loading resources. Please file a bug report.", mre);
}
}
public static String getText(String key) {
return getText(key, null, null);
}
private static String getText(String key, String a1, String a2){
if (m == null)
initMessages();
try {
return MessageFormat.format(m.getString(key),
new String[] { a1, a2 });
} catch (MissingResourceException e) {
fatal("Key " + key + " not found in resources.", e);
}
return null; /* dead code */
}
/*
* Usage message.
*/
public static void usage(int exitValue) {
if (exitValue == 0) {
System.out.println(getText("usage"));
} else {
System.err.println(getText("usage"));
}
System.exit(exitValue);
}
public static void version() {
System.out.println(getText("javah.version",
System.getProperty("java.version"), null));
System.exit(0);
}
/*
* Failure modes.
*/
public static void bug(String key) {
bug(key, null);
}
public static void bug(String key, Exception e) {
if (e != null)
e.printStackTrace();
System.err.println(getText(key));
System.err.println(getText("bug.report"));
System.exit(11);
}
public static void error(String key) {
error(key, null);
}
public static void error(String key, String a1) {
error(key, a1, null);
}
public static void error(String key, String a1, String a2) {
error(key, a1, a2, false);
}
public static void error(String key, String a1, String a2,
boolean showUsage) {
System.err.println("Error: " + getText(key, a1, a2));
if (showUsage)
usage(15);
System.exit(15);
}
private static void fatal(String msg) {
fatal(msg, null);
}
private static void fatal(String msg, Exception e) {
if (e != null) {
e.printStackTrace();
}
System.err.println(msg);
System.exit(10);
}
/*
* Support for platform specific things in javah, such as pragma
* directives, exported symbols etc.
*/
static ResourceBundle platform = null;
static String getPlatformString(String key) {
if (platform == null)
initPlatform();
try {
return platform.getString(key);
} catch (MissingResourceException mre) {
return null;
}
}
private static void initPlatform() {
String os = System.getProperty("os.name");
if (os.startsWith("Windows"))
os = "win32";
String arch = System.getProperty("os.arch");
String resname = "com.sun.tools.javah.resources." + os + "_" + arch;
try {
platform=ResourceBundle.getBundle(resname);
} catch (MissingResourceException mre) {
fatal("Error loading resources. Please file a bug report.", mre);
}
}
}
/*
* The end.
*/

View File

@@ -0,0 +1,15 @@
/*
* Not used.
*/
package com.compilercompany.es3c.v1;
interface Attributes {
static final int ReadOnly = 0x00000001;
static final int DontDelete = 0x00000002;
static final int DontEnum = 0x00000004;
}
/*
* The end.
*/

View File

@@ -0,0 +1,31 @@
package com.compilercompany.es3c.v1;
/**
* Represents a basic block for flow analysis.
*/
public class Block {
Node entry, exit;
int n;
Block(int n) {
this.n = n;
}
void setEntry( Node entry ) {
this.entry = entry;
}
void setExit( Node exit ) {
this.exit = exit;
}
public String toString() {
return "B"+n/*+"( " + entry + ", " + exit + " )"*/;
}
}
/*
* The end.
*/

View File

@@ -0,0 +1,214 @@
package com.compilercompany.es3c.v1;
import java.util.Stack;
import java.util.Vector;
import java.util.Enumeration;
import java.util.Hashtable;
/**
* Context used during semantic analysis.
*/
public class Context {
private static final boolean debug = true;
Evaluator evaluator;
Stack scopeStack;
Stack classStack;
Scope global;
Hashtable predecessors = new Hashtable();
Hashtable D;
int indent = 0;
int errors = 0;
public int errorCount() {
return errors;
}
String getIndent() {
StringBuffer str = new StringBuffer();
for (int i = 0; i < indent; i++) {
str.append('\t');
}
return str.toString();
}
/**
*
*/
static InputBuffer in;
public static InputBuffer getInput() {
return in;
}
public static void init(InputBuffer input) {
in=input;
}
/**
*
*/
public Evaluator getEvaluator() {
return evaluator;
}
public void setEvaluator(Evaluator evaluator) {
this.evaluator=evaluator;
}
/**
* The bottom of the stack.
*/
Scope getGlobal() {
return global;
}
/**
* The top of the scope stack.
*/
Scope getLocal() {
return (Scope) scopeStack.peek();
}
/**
* Make the given scope the new innermost scope.
*/
public Scope pushScope(Scope scope) {
if( scopeStack==null ) {
scopeStack = new Stack();
global = scope;
}
scopeStack.push(scope);
return scope;
}
/**
* Pop the top scope off the stack.
*/
public void popScope() {
if( scopeStack==null ) {
return;
}
scopeStack.pop();
return;
}
/**
* Make the given scope the new innermost scope.
*/
void enterClass(Scope scope) {
pushScope(scope);
if( classStack==null ) {
classStack = new Stack();
}
classStack.push(scope);
return;
}
void exitClass() {
classStack.pop();
popScope();
return;
}
Scope getThisClass() {
if(classStack.size()==0) {
return global;
} else {
return (Scope) classStack.peek();
}
}
/**
* The immediate outer.
*/
Scope nextScope(Scope scope) {
Scope next;
int index = scopeStack.indexOf(scope);
if(index==0) {
next = null;
} else {
next = (Scope) scopeStack.elementAt(index-1);
}
return next;
}
private Block thisBlock;
Vector blocks = new Vector();
int blockCount;
void enterBlock(Node entry) throws Exception {
if( debug ) {
Debugger.trace("Context.enterBlock() with entry = " + entry );
//Thread.dumpStack();
//if(entry instanceof AnnotatedBlockNode) throw new Exception("blah");
}
if( thisBlock!=null ) {
throw new Exception("Entering block before exiting previous block.");
}
thisBlock = new Block(blockCount++);
thisBlock.setEntry(entry);
blocks.addElement(thisBlock);
}
Block getBlock() {
return thisBlock;
}
void setBlock(Block b) {
thisBlock=b;
}
void exitBlock(Node exit) {
if( debug ) {
Debugger.trace("Context.exitBlock() with exit = " + exit );
}
if(thisBlock!=null) {
thisBlock.setExit(exit);
thisBlock = null;
}
}
/**
* Get all basic blocks in the current program.
*/
public Vector getBlocks() {
return blocks;
}
/**
* Add an edge.
*/
void addEdge(Block b1, Block b2) {
if( debug ) {
Debugger.trace("Context.addEdge() with b1 = " + b1 + ", b2 = " + b2 );
}
Vector preds = (Vector) predecessors.get(b2);
if( preds == null ) {
preds = new Vector();
preds.addElement(b1);
predecessors.put(b2,preds);
} else if( !preds.contains(b1) ) {
preds.addElement(b1);
}
}
public String toString() { return "context( " + scopeStack + ", " + global + " )"; }
}
/*
* The end.
*/

View File

@@ -0,0 +1,16 @@
package com.compilercompany.es3c.v1;
/**
* Not used.
**/
public interface Errors {
static final String syntaxPart1_error = "Error at: ";
static final String syntaxPart2_error = " Expecting a ";
}
/*
* The end.
*/

View File

@@ -0,0 +1,243 @@
package com.compilercompany.es3c.v1;
/**
* The base visitor object extended by semantic evaluators.
*
* This is a visitor that is used by the compiler for various forms for
* evaluation of a parse tree (e.g. a type evaluator might compute the
* static type of an expression.)
*/
public class Evaluator {
Value evaluate( Context context, Node node ) throws Exception {
throw new Exception( "synthesis unspecified for node = " + node );
}
// Expression evaluators
Value evaluate( Context context, ThisExpressionNode node ) throws Exception {
throw new Exception( "synthesis unspecified for node = " + node );
}
Value evaluate( Context context, IdentifierNode node ) throws Exception {
throw new Exception( "synthesis unspecified for node = " + node );
}
Value evaluate( Context context, QualifiedIdentifierNode node ) throws Exception {
throw new Exception( "synthesis unspecified for node = " + node );
}
Value evaluate( Context context, LiteralBooleanNode node ) throws Exception {
throw new Exception( "synthesis unspecified for node = " + node );
}
Value evaluate( Context context, LiteralNullNode node ) throws Exception {
throw new Exception( "synthesis unspecified for node = " + node );
}
Value evaluate( Context context, LiteralNumberNode node ) throws Exception {
throw new Exception( "synthesis unspecified for node = " + node );
}
Value evaluate( Context context, LiteralStringNode node ) throws Exception {
throw new Exception( "synthesis unspecified for node = " + node );
}
Value evaluate( Context context, LiteralUndefinedNode node ) throws Exception {
throw new Exception( "synthesis unspecified for node = " + node );
}
Value evaluate( Context context, LiteralRegExpNode node ) throws Exception {
throw new Exception( "synthesis unspecified for node = " + node );
}
Value evaluate( Context context, UnitExpressionNode node ) throws Exception {
throw new Exception( "synthesis unspecified for node = " + node );
}
Value evaluate( Context context, FunctionExpressionNode node ) throws Exception {
throw new Exception( "synthesis unspecified for node = " + node );
}
Value evaluate( Context context, ParenthesizedExpressionNode node ) throws Exception {
throw new Exception( "synthesis unspecified for node = " + node );
}
Value evaluate( Context context, ParenthesizedListExpressionNode node ) throws Exception {
throw new Exception( "synthesis unspecified for node = " + node );
}
Value evaluate( Context context, LiteralObjectNode node ) throws Exception {
throw new Exception( "synthesis unspecified for node = " + node );
}
Value evaluate( Context context, LiteralFieldNode node ) throws Exception {
throw new Exception( "synthesis unspecified for node = " + node );
}
Value evaluate( Context context, LiteralArrayNode node ) throws Exception {
throw new Exception( "synthesis unspecified for node = " + node );
}
Value evaluate( Context context, PostfixExpressionNode node ) throws Exception {
throw new Exception( "synthesis unspecified for node = " + node );
}
Value evaluate( Context context, NewExpressionNode node ) throws Exception {
throw new Exception( "synthesis unspecified for node = " + node );
}
Value evaluate( Context context, IndexedMemberExpressionNode node ) throws Exception {
throw new Exception( "synthesis unspecified for node = " + node );
}
Value evaluate( Context context, ClassofExpressionNode node ) throws Exception {
throw new Exception( "synthesis unspecified for node = " + node );
}
Value evaluate( Context context, MemberExpressionNode node ) throws Exception {
throw new Exception( "synthesis unspecified for node = " + node );
}
Value evaluate( Context context, CoersionExpressionNode node ) throws Exception {
throw new Exception( "synthesis unspecified for node = " + node );
}
Value evaluate( Context context, CallExpressionNode node ) throws Exception {
throw new Exception( "synthesis unspecified for node = " + node );
}
Value evaluate( Context context, UnaryExpressionNode node ) throws Exception {
throw new Exception( "synthesis unspecified for node = " + node );
}
Value evaluate( Context context, BinaryExpressionNode node ) throws Exception {
throw new Exception( "synthesis unspecified for node = " + node );
}
Value evaluate( Context context, ConditionalExpressionNode node ) throws Exception {
throw new Exception( "synthesis unspecified for node = " + node );
}
Value evaluate( Context context, AssignmentExpressionNode node ) throws Exception {
throw new Exception( "synthesis unspecified for node = " + node );
}
Value evaluate( Context context, ListNode node ) throws Exception {
throw new Exception( "synthesis unspecified for node = " + node );
}
// Statements
Value evaluate( Context context, StatementListNode node ) throws Exception {
throw new Exception( "synthesis unspecified for node = " + node );
}
Value evaluate( Context context, EmptyStatementNode node ) throws Exception {
throw new Exception( "synthesis unspecified for node = " + node );
}
Value evaluate( Context context, ExpressionStatementNode node ) throws Exception {
throw new Exception( "synthesis unspecified for node = " + node );
}
Value evaluate( Context context, AnnotatedBlockNode node ) throws Exception {
throw new Exception( "synthesis unspecified for node = " + node );
}
Value evaluate( Context context, LabeledStatementNode node ) throws Exception {
throw new Exception( "synthesis unspecified for node = " + node );
}
Value evaluate( Context context, IfStatementNode node ) throws Exception {
throw new Exception( "synthesis unspecified for node = " + node );
}
Value evaluate( Context context, SwitchStatementNode node ) throws Exception {
throw new Exception( "synthesis unspecified for node = " + node );
}
Value evaluate( Context context, CaseLabelNode node ) throws Exception {
throw new Exception( "synthesis unspecified for node = " + node );
}
Value evaluate( Context context, DoStatementNode node ) throws Exception {
throw new Exception( "synthesis unspecified for node = " + node );
}
Value evaluate( Context context, WhileStatementNode node ) throws Exception {
throw new Exception( "synthesis unspecified for node = " + node );
}
Value evaluate( Context context, ForInStatementNode node ) throws Exception {
throw new Exception( "synthesis unspecified for node = " + node );
}
Value evaluate( Context context, ForStatementNode node ) throws Exception {
throw new Exception( "synthesis unspecified for node = " + node );
}
Value evaluate( Context context, WithStatementNode node ) throws Exception {
throw new Exception( "synthesis unspecified for node = " + node );
}
Value evaluate( Context context, ContinueStatementNode node ) throws Exception {
throw new Exception( "synthesis unspecified for node = " + node );
}
Value evaluate( Context context, BreakStatementNode node ) throws Exception {
throw new Exception( "synthesis unspecified for node = " + node );
}
Value evaluate( Context context, ReturnStatementNode node ) throws Exception {
throw new Exception( "synthesis unspecified for node = " + node );
}
Value evaluate( Context context, ThrowStatementNode node ) throws Exception {
throw new Exception( "synthesis unspecified for node = " + node );
}
Value evaluate( Context context, TryStatementNode node ) throws Exception {
throw new Exception( "synthesis unspecified for node = " + node );
}
Value evaluate( Context context, CatchClauseNode node ) throws Exception {
throw new Exception( "synthesis unspecified for node = " + node );
}
Value evaluate( Context context, FinallyClauseNode node ) throws Exception {
throw new Exception( "synthesis unspecified for node = " + node );
}
Value evaluate( Context context, UseStatementNode node ) throws Exception {
throw new Exception( "synthesis unspecified for node = " + node );
}
Value evaluate( Context context, IncludeStatementNode node ) throws Exception {
throw new Exception( "synthesis unspecified for node = " + node );
}
// Definitions
Value evaluate( Context context, ImportDefinitionNode node ) throws Exception {
throw new Exception( "synthesis unspecified for node = " + node );
}
Value evaluate( Context context, ImportBindingNode node ) throws Exception {
throw new Exception( "synthesis unspecified for node = " + node );
}
Value evaluate( Context context, AnnotatedDefinitionNode node ) throws Exception {
throw new Exception( "evaluation unspecified for node = " + node );
}
Value evaluate( Context context, AttributeListNode node ) throws Exception {
throw new Exception( "evaluation unspecified for node = " + node );
}
Value evaluate( Context context, ExportDefinitionNode node ) throws Exception {
throw new Exception( "evaluation unspecified for node = " + node );
}
Value evaluate( Context context, ExportBindingNode node ) throws Exception {
throw new Exception( "evaluation unspecified for node = " + node );
}
Value evaluate( Context context, VariableDefinitionNode node ) throws Exception {
throw new Exception( "evaluation unspecified for node = " + node );
}
Value evaluate( Context context, VariableBindingNode node ) throws Exception {
throw new Exception( "evaluation unspecified for node = " + node );
}
Value evaluate( Context context, TypedVariableNode node ) throws Exception {
throw new Exception( "evaluation unspecified for node = " + node );
}
Value evaluate( Context context, FunctionDefinitionNode node ) throws Exception {
throw new Exception( "evaluation unspecified for node = " + node );
}
Value evaluate( Context context, FunctionDeclarationNode node ) throws Exception {
throw new Exception( "evaluation unspecified for node = " + node );
}
Value evaluate( Context context, FunctionNameNode node ) throws Exception {
throw new Exception( "evaluation unspecified for node = " + node );
}
Value evaluate( Context context, FunctionSignatureNode node ) throws Exception {
throw new Exception( "evaluation unspecified for node = " + node );
}
Value evaluate( Context context, ParameterNode node ) throws Exception {
throw new Exception( "evaluation unspecified for node = " + node );
}
Value evaluate( Context context, OptionalParameterNode node ) throws Exception {
throw new Exception( "evaluation unspecified for node = " + node );
}
Value evaluate( Context context, ClassDefinitionNode node ) throws Exception {
throw new Exception( "evaluation unspecified for node = " + node );
}
Value evaluate( Context context, ClassDeclarationNode node ) throws Exception {
throw new Exception( "evaluation unspecified for node = " + node );
}
Value evaluate( Context context, InheritanceNode node ) throws Exception {
throw new Exception( "synthesis unspecified for node = " + node );
}
Value evaluate( Context context, NamespaceDefinitionNode node ) throws Exception {
throw new Exception( "evaluation unspecified for node = " + node );
}
Value evaluate( Context context, PackageDefinitionNode node ) throws Exception {
throw new Exception( "evaluation unspecified for node = " + node );
}
Value evaluate( Context context, ProgramNode node ) throws Exception {
throw new Exception( "evaluation unspecified for node = " + node );
}
}
/*
* The end.
*/

View File

@@ -0,0 +1,18 @@
package com.compilercompany.es3c.v1;
/**
* Interface that object initializers implement.
*
* This interface is implemented by objects that can build
* instances of the Value class. For example, there is an
* object class that implements this interface for the
* system global object.
*/
interface Init {
void init( Value ob ) throws Exception;
}
/*
* The end.
*/

View File

@@ -0,0 +1,64 @@
package com.compilercompany.es3c.v1;
/**
* The base Node class.
*/
public class Node {
private static final boolean debug = false;
Block block;
int position;
Store store;
public Node() {
}
public Node( int position ) {
this.position = position;
}
public Value evaluate( Context context, Evaluator evaluator ) throws Exception {
return null;
}
boolean isLeader;
public void markLeader() throws Exception {
if( debug ) {
Debugger.trace( "Node.markLeader() with this = " + this );
//if(this instanceof AnnotatedBlockNode) throw new Exception("blah");
}
isLeader=true;
}
public boolean isLeader() {
return isLeader;
}
public boolean isBranch() {
return false;
}
public Node[] getTargets() {
return null;
}
public Node first() {
return this;
}
public Node last() {
return this;
}
public Node pos(int p) {
position = p;
return this;
}
public int pos() {
return position;
}
public String toString() {
return isLeader ? "*"+block+":" : ""+block+":";
}
}
/*
* The end.
*/

View File

@@ -0,0 +1,273 @@
/*
* Creates parse tree nodes.
*/
package com.compilercompany.es3c.v1;
public final class NodeFactory {
private static final boolean debug = false;
static private InputBuffer in;
static void init(InputBuffer input) {
in = input;
}
static IdentifierNode Identifier( String name ) {
if( debug ) {
Debugger.trace("" + in.positionOfMark() + ": Identifier " + name );
}
return new IdentifierNode(name,in.positionOfMark());
}
static QualifiedIdentifierNode QualifiedIdentifier( Node qualifier, IdentifierNode identifier ) {
if( debug ) {
Debugger.trace("" + in.positionOfMark() + ": QualifiedIdentifier " + identifier);
}
return new QualifiedIdentifierNode(qualifier,identifier,identifier.pos());
}
static LiteralNullNode LiteralNull() {
return new LiteralNullNode();
}
static LiteralBooleanNode LiteralBoolean(boolean value) {
return new LiteralBooleanNode(value);
}
static LiteralArrayNode LiteralArray( Node elementlist ) {
return new LiteralArrayNode(elementlist);
}
static LiteralFieldNode LiteralField( Node name, Node value ) {
return new LiteralFieldNode(name,value);
}
static LiteralNumberNode LiteralNumber( String value ) {
return new LiteralNumberNode(value);
}
static LiteralObjectNode LiteralObject( Node fieldlist ) {
return new LiteralObjectNode(fieldlist);
}
static LiteralRegExpNode LiteralRegExp( String value ) {
return new LiteralRegExpNode(value);
}
static LiteralStringNode LiteralString( String value ) {
return new LiteralStringNode(value);
}
static LiteralTypeNode LiteralType( Type type ) {
return new LiteralTypeNode(type);
}
static LiteralUndefinedNode LiteralUndefined() {
return new LiteralUndefinedNode();
}
static ParenthesizedExpressionNode ParenthesizedExpression( Node expr ) {
return new ParenthesizedExpressionNode(expr,in.positionOfMark());
}
static ParenthesizedListExpressionNode ParenthesizedListExpression( Node expr ) {
return new ParenthesizedListExpressionNode(expr);
}
static FunctionExpressionNode FunctionExpression( Node name, Node signature, Node body ) {
return new FunctionExpressionNode(name,signature,body);
}
static AnnotatedDefinitionNode AnnotatedDefinition( Node attributes, Node definition ) {
return new AnnotatedDefinitionNode(attributes,definition);
}
static AttributeListNode AttributeList( Node item, Node list ) {
return new AttributeListNode(item,list);
}
static UnitExpressionNode UnitExpression( Node value, Node type ) {
return new UnitExpressionNode(value,type);
}
static ThisExpressionNode ThisExpression() {
return new ThisExpressionNode();
}
static SuperExpressionNode SuperExpression() {
return new SuperExpressionNode();
}
static ListNode List( Node list, Node item ) {
return new ListNode(list,item,item.pos());
}
static PostfixExpressionNode PostfixExpression( int op, Node expr ) {
return new PostfixExpressionNode(op,expr);
}
static NewExpressionNode NewExpression( Node member ) {
return new NewExpressionNode(member);
}
static ClassofExpressionNode ClassofExpression( Node base ) {
if( debug ) {
Debugger.trace("base = " + base);
}
return new ClassofExpressionNode(base);
}
static CallExpressionNode CallExpression( Node member, Node args ) {
return new CallExpressionNode(member,args);
}
static IndexedMemberExpressionNode IndexedMemberExpression( Node base, Node member ) {
return new IndexedMemberExpressionNode(base,member,in.positionOfMark());
}
static MemberExpressionNode MemberExpression( Node base, Node name ) {
return new MemberExpressionNode(base,name,in.positionOfMark());
}
static CoersionExpressionNode CoersionExpression( Node expr, Node type ) {
return new CoersionExpressionNode(expr,type,in.positionOfMark());
}
static UnaryExpressionNode UnaryExpression( int op, Node expr ) {
return new UnaryExpressionNode(op,expr);
}
static BinaryExpressionNode BinaryExpression( int op, Node lhs, Node rhs ) {
return new BinaryExpressionNode(op,lhs,rhs);
}
static ConditionalExpressionNode ConditionalExpression( Node cond, Node thenexpr, Node elseexpr ) {
return new ConditionalExpressionNode(cond,thenexpr,elseexpr);
}
static AssignmentExpressionNode AssignmentExpression( Node lhs, int op, Node rhs ) {
return new AssignmentExpressionNode(lhs,op,rhs);
}
static StatementListNode StatementList( StatementListNode list, Node item ) {
return new StatementListNode(list,item);
}
static EmptyStatementNode EmptyStatement() {
return new EmptyStatementNode();
}
static ExpressionStatementNode ExpressionStatement( Node expr ) {
return new ExpressionStatementNode(expr);
}
static AnnotatedBlockNode AnnotatedBlock( Node attributes, Node definition ) {
return new AnnotatedBlockNode(attributes,definition);
}
static LabeledStatementNode LabeledStatement( Node label, Node statement ) {
return new LabeledStatementNode(label,statement);
}
static IfStatementNode IfStatement( Node test, Node tblock, Node eblock ) {
return new IfStatementNode(test,tblock,eblock);
}
static SwitchStatementNode SwitchStatement( Node expr, StatementListNode statements ) {
return new SwitchStatementNode(expr,statements);
}
static CaseLabelNode CaseLabel( Node label ) {
return new CaseLabelNode(label);
}
static DoStatementNode DoStatement( Node block, Node expr ) {
return new DoStatementNode(block,expr);
}
static WhileStatementNode WhileStatement( Node expr, Node statement ) {
return new WhileStatementNode(expr,statement);
}
static ForInStatementNode ForInStatement( Node expr1, Node expr2, Node statement ) {
return new ForInStatementNode(expr1,expr2,statement);
}
static ForStatementNode ForStatement( Node expr1, Node expr2, Node expr3, Node statement ) {
return new ForStatementNode(expr1,expr2,expr3,statement);
}
static WithStatementNode WithStatement( Node expr, Node statement ) {
return new WithStatementNode(expr,statement);
}
static ContinueStatementNode ContinueStatement(Node expr) {
return new ContinueStatementNode(expr);
}
static BreakStatementNode BreakStatement(Node expr) {
return new BreakStatementNode(expr);
}
static ReturnStatementNode ReturnStatement( Node expr ) {
return new ReturnStatementNode(expr);
}
static ThrowStatementNode ThrowStatement(Node list) {
return new ThrowStatementNode(list);
}
static TryStatementNode TryStatement(Node tryblock, StatementListNode catchlist, Node finallyblock) {
return new TryStatementNode(tryblock,catchlist,finallyblock);
}
static CatchClauseNode CatchClause(Node parameter, Node block) {
return new CatchClauseNode(parameter,block);
}
static FinallyClauseNode FinallyClause( Node block ) {
return new FinallyClauseNode(block);
}
static IncludeStatementNode IncludeStatement( Node list ) {
return new IncludeStatementNode(list);
}
static UseStatementNode UseStatement( Node expr ) {
return new UseStatementNode(expr);
}
static ImportDefinitionNode ImportDefinition( Node item, Node list ) {
return new ImportDefinitionNode(item,list);
}
static ImportBindingNode ImportBinding( Node identifer, Node item ) {
return new ImportBindingNode(identifer,item);
}
static ExportDefinitionNode ExportDefinition( Node list ) {
return new ExportDefinitionNode(list);
}
static ExportBindingNode ExportBinding( Node name, Node value ) {
return new ExportBindingNode(name,value);
}
static VariableDefinitionNode VariableDefinition( int kind, Node list ) {
return new VariableDefinitionNode(kind,list,list.pos());
}
static VariableBindingNode VariableBinding( Node identifier, Node initializer ) {
return new VariableBindingNode(identifier,initializer);
}
static TypedVariableNode TypedVariable( Node identifier, Node type ) {
if( debug ) {
Debugger.trace("" + in.positionOfMark() + ": TypedVariable " + type );
}
return new TypedVariableNode(identifier,type,type!=null?type.pos():identifier.pos());
}
static FunctionDefinitionNode FunctionDefinition( Node decl, Node body ) {
return new FunctionDefinitionNode(decl,body);
}
static FunctionDeclarationNode FunctionDeclaration( Node name, Node signature ) {
return new FunctionDeclarationNode(name,signature);
}
static FunctionNameNode FunctionName( int kind, Node name ) {
return new FunctionNameNode(kind,name);
}
static RestParameterNode RestParameter( Node expr ) {
return new RestParameterNode(expr);
}
static ParameterNode Parameter( Node identifer, Node type ) {
return new ParameterNode(identifer,type);
}
static OptionalParameterNode OptionalParameter( Node identifer, Node init ) {
return new OptionalParameterNode(identifer,init);
}
static NamedParameterNode NamedParameter( Node name, Node parameter ) {
return new NamedParameterNode(name,parameter);
}
static ClassDeclarationNode ClassDeclaration( Node name ) {
return new ClassDeclarationNode(name);
}
static ClassDefinitionNode ClassDefinition( Node name, Node interfaces, Node statements ) {
return new ClassDefinitionNode(name,interfaces,statements);
}
static InheritanceNode Inheritance( Node baseclass, Node interfaces ) {
return new InheritanceNode(baseclass,interfaces);
}
static InterfaceDeclarationNode InterfaceDeclaration( Node name ) {
return new InterfaceDeclarationNode(name);
}
static InterfaceDefinitionNode InterfaceDefinition( Node name, Node interfaces, Node statements ) {
return new InterfaceDefinitionNode(name,interfaces,statements);
}
static NamespaceDefinitionNode NamespaceDefinition( Node identifier, Node list ) {
return new NamespaceDefinitionNode(identifier,list);
}
static LanguageDeclarationNode LanguageDeclaration( Node list ) {
return new LanguageDeclarationNode(list);
}
static PackageDefinitionNode PackageDefinition( Node name, Node block ) {
return new PackageDefinitionNode(name,block);
}
static ProgramNode Program( Node statements ) {
return new ProgramNode(statements);
}
/*
static Node () {
return new Node();
}
*/
}
/*
* The end.
*/

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,15 @@
package com.compilercompany.es3c.v1;
/**
* A scope, which contains slots.
*/
public interface Scope {
Slot get(Value namespace, String name) throws Exception;
Slot add(Value namespace, String name ) throws Exception;
boolean has(Value namespace, String name) throws Exception;
}
/*
* The end.
*/

View File

@@ -0,0 +1,21 @@
package com.compilercompany.es3c.v1;
/**
* A slot.
*/
public class Slot {
Value attrs;
Value type;
Value value;
Block block;
Store store;
public String toString() {
return "{ "+attrs+", "+type+", "+value+", "+store+" }";
}
}
/*
* The end.
*/

View File

@@ -0,0 +1,23 @@
package com.compilercompany.es3c.v1;
/**
* Represents an abstract unit of storage.
*/
public class Store {
Scope scope;
int index;
Store(Scope scope, int index) {
this.scope = scope;
this.index = index;
}
public String toString() {
return "store( " + index + " )";
}
}
/*
* The end.
*/

View File

@@ -0,0 +1,20 @@
package com.compilercompany.es3c.v1;
/**
* The interfaces for all types.
*/
public interface Type extends Init {
Object[] values();
Type[] converts();
void addSub(Type type);
boolean includes(Value value);
void setSuper(Type type);
Type getSuper();
Value convert(Context context, Value value) throws Exception;
Value coerce(Context context, Value value) throws Exception;
}
/*
* The end.
*/

View File

@@ -0,0 +1,92 @@
package com.compilercompany.es3c.v1;
import java.util.Hashtable;
import java.util.Vector;
/**
* The value class from which all other values derive.
*/
abstract public class Value implements Scope {
private static final boolean debug = false;
public Value type;
public Value getValue(Context context) throws Exception { return this; }
public Value getType(Context context) throws Exception { return type; }
/*
Hashtable defaultNames = new Hashtable();
Hashtable namespaces = new Hashtable();
Hashtable attributes = new Hashtable();
*/
public boolean has(Value namespace, String name) throws Exception {
throw new Exception("Constructor object expected in new expression");
/*
Hashtable names;
if( namespace == null ) {
names = defaultNames;
} else {
names = (Hashtable) namespaces.get(namespace);
}
return names.containsKey(name);
*/
}
public Slot get(Value namespace, String name) throws Exception {
throw new Exception("Constructor object expected in new expression");
/*
if(debug) {
Debugger.trace("ObjectValue.get() with namespaces="+namespaces+", namespace="+namespace+", name="+name);
}
Hashtable names;
if( namespace == null ) {
names = defaultNames;
} else {
names = (Hashtable) namespaces.get(namespace);
}
return (Slot) names.get(name);
*/
}
public Slot add(Value namespace, String name) throws Exception {
throw new Exception("Constructor object expected in new expression");
/*
if( debug ) {
Debugger.trace("ObjectType.add() with this = " + this + " namespace = " + namespace + " name = " + name);
}
Hashtable names;
if( namespace == null ) {
names = defaultNames;
} else {
names = (Hashtable) namespaces.get(namespace);
if( names==null ) {
names = new Hashtable();
namespaces.put(namespace,names);
}
}
Slot slot = new Slot();
names.put(name,slot);
return slot;
*/
}
int size() {
return 0;
}
public Value construct(Context context, Value args) throws Exception {
throw new Exception("Constructor object expected in new expression");
}
public Value call(Context context, Value args) throws Exception {
throw new Exception("Callable object expected in call expression");
}
}
/*
* The end.
*/

View File

@@ -0,0 +1,962 @@
package com.compilercompany.es3c.v1;
import java.io.*;
import java.lang.reflect.*;
import java.util.*;
/**
* Delineates the program into its basic execution blocks.
*
* It is necessary to know all the blocks in the program
* before we can mark the flow-control edges and compute
* the dominance relationship between a reference and
* definition.
*
* The algorithm for partitioning the program into basic
* blocks goes like this:
* 1 Identify leaders.
* 1.1 The first statement of a program.
* 1.2 The target of a branch.
* 1.3 Immediately follows a branch.
* 1.2 Create a block with entry = leader, exit =
* 2.Identify exits.
* 3 Enter a new block at each leader.
* 4 Exit the current block when an exit is encountered.
*/
public class BlockEvaluator extends Evaluator {
private static final boolean debug = false;
/**
* ExpressionStatementNode
*
* Semantics:
* 1. Tag node with current block label.
* 2. Return.
*/
Value evaluate( Context context, ExpressionStatementNode node ) throws Exception {
if( debug ) {
Debugger.trace("defining ExpressionStatementNode = " + node);
}
node.block = context.getBlock();
return UndefinedValue.undefinedValue;
}
/**
* EmptyStatementNode
*
* Semantics:
* 1. Tag node with current block label.
* 2. Return undefined.
*/
Value evaluate( Context context, EmptyStatementNode node ) throws Exception {
if( debug ) {
Debugger.trace("defining ExpressionStatementNode = " + node);
}
node.block = context.getBlock();
return UndefinedValue.undefinedValue;
}
/**
* AnnotatedBlockNode
*
* Syntax:
* { attributes:list statements:list }
*
* Semantics:
* 1. Tag node with current block label.
* 2. Exit current block.
* 3. Mark first statement of block, a leader.
* 4. Evaluate statements.
* 5. Return.
*
* Notes:
* The attributes reside in the preceding block. The first statement is
* the leader of a new block since a boolean typed attribute affects
* whether this statement list gets included in the control-flow of the
* program. The next pass will determine if there is a false valued
* attribute and exclude this block from the edges that lead from the
* preceding block.
*/
Value evaluate( Context context, AnnotatedBlockNode node ) throws Exception {
if( debug ) {
Debugger.trace("evaluating AnnotatedBlockNode = " + node);
}
node.block = context.getBlock();
context.exitBlock(node);
node.statements.first().markLeader();
node.statements.evaluate(context,this);
return UndefinedValue.undefinedValue;
}
/**
* StatementListNode
*/
Value evaluate( Context context, StatementListNode node ) throws Exception {
if( debug ) {
Debugger.trace("defining StatementListNode = " + node);
}
ListValue list;
if( node.list != null ) {
if( node.list instanceof StatementListNode ) {
list = (ListValue) node.list.evaluate(context,this);
} else {
list = new ListValue();
list.push(node.list.evaluate(context,this));
}
} else {
list = new ListValue();
}
if( node.item != null ) {
Node item = node.item;
StatementListNode prev = (StatementListNode)node.list;
// Mark leaders.
if( prev != null && prev.item.isBranch() ) {
item.markLeader();
}
if( item.isBranch() ) {
Node[] targets = item.getTargets();
if( targets!=null ) {
for(int i=0;i<targets.length;i++) {
Debugger.trace("targets[i]="+targets[i]);
targets[i].markLeader();
}
}
}
if( prev != null && item.isLeader() ) { // This should only happen with case labels.
context.exitBlock(prev);
}
if( item.isLeader() ) {
context.enterBlock(item);
}
item.evaluate(context,this);
}
else {
context.exitBlock(node.list.item);
}
return list;
}
static final void testStatementList() throws Exception {
String[] input = {
"x=1;y=2;z=3;",
"if(x) {x=1;y=2;}",
"class C {} a=0; if(x) {var x:C;y=2;} else { z=3; } var c:C; c;",
"a=0; if(x) {x=1;y=2;} else { class C {} z=3; } d=4; var c:C; c;",
};
String[] expected = {
"",
"",
"",
"",
};
testEvaluator("AnnotatedDefinition",input,expected);
}
/**
* LabeledStatementNode
*
* Semantics:
* 1 Tag node with current block label.
* 2 Evaluate statement.
* 3 Exit the current block.
* 4 Return.
*/
Value evaluate( Context context, LabeledStatementNode node ) throws Exception {
if( debug ) {
Debugger.trace("defining LabeledStatementNode = " + node);
}
// Point the current statement to its block.
// This reference will be used to compute dominators.
node.block = context.getBlock();
node.statement.evaluate(context,this);
context.exitBlock(node.statement.last());
return UndefinedValue.undefinedValue;
}
/**
* IfStatementNode
*
* Semantics:
* 1. Tag node with current block label.
* 2. Exit current block.
* 3. Mark as leader the first statement of then block.
* 4. Evaluate the then block statements.
* 5. Exit the current block.
* 6. Mark as leader the first statement of else block.
* 7. Evaluate the else block statements.
* 8. Exit the current block.
* 9. Return.
*/
Value evaluate( Context context, IfStatementNode node ) throws Exception {
if( debug ) {
Debugger.trace("evaluating Node = " + node);
}
node.block = context.getBlock();
context.exitBlock(node.condition);
node.thenactions.markLeader();
context.enterBlock(node.thenactions);
node.thenactions.block = context.getBlock();
node.thenactions.evaluate(context,this);
context.exitBlock(node.thenactions.last());
if( node.elseactions!=null ) {
node.elseactions.markLeader();
context.enterBlock(node.elseactions);
node.elseactions.block = context.getBlock();
node.elseactions.evaluate(context,this);
context.exitBlock(node.elseactions.last());
}
return UndefinedValue.undefinedValue;
}
/**
* SwitchStatementNode
*
* { expr, statements }
*
* Semantics:
* 1. Tag node with current block label.
* 2. Exit current block.
* 3. Mark as leader the first statement of statement list.
* 4. Evaluate the statement list.
* 5. Exit the current block.
* 9. Return.
*/
Value evaluate( Context context, SwitchStatementNode node ) throws Exception {
if( debug ) {
Debugger.trace("evaluating Node = " + node);
}
node.block = context.getBlock();
context.exitBlock(node.expr);
node.statements.evaluate(context,this);
return UndefinedValue.undefinedValue;
}
/**
* CaseLabelNode
* { label }
* if label is null, then its the default case.
*
* Semantics:
* 1 Tag node with current block label.
* 4 Return.
*/
Value evaluate( Context context, CaseLabelNode node ) throws Exception {
if( debug ) {
Debugger.trace("defining CaseLabelNode = " + node);
}
node.block = context.getBlock();
return UndefinedValue.undefinedValue;
}
/**
* DoStatementNode
*
* { statements, expr }
*
* Semantics:
* 1 Tag node with current block label.
* 2 Evaluate statements.
* 3 Exit the current block.
* 4 Return.
*/
Value evaluate( Context context, DoStatementNode node ) throws Exception {
if( debug ) {
Debugger.trace("evaluating DoStatementNode = " + node);
}
node.block = context.getBlock();
node.statements.evaluate(context,this);
context.exitBlock(node.expr);
return UndefinedValue.undefinedValue;
}
/**
* WhileStatementNode
*
* { expr, statement }
*
* Semantics:
* 1 Tag node with current block label.
* 2 Evaluate statements.
* 3 Exit the current block.
* 4 Return.
*/
Value evaluate( Context context, WhileStatementNode node ) throws Exception {
if( debug ) {
Debugger.trace("evaluating WhileStatementNode = " + node);
}
node.block = context.getBlock();
context.exitBlock(node);
context.enterBlock(node.statement);
node.statement.evaluate(context,this);
context.exitBlock(node.statement.last());
return UndefinedValue.undefinedValue;
}
/**
* ForStatementNode
*
* { initialize, test, increment, statement }
*
* Semantics:
* 1 Tag node with current block label.
* 2 Evaluate statements.
* 3 Exit the current block.
* 4 Return.
*/
Value evaluate( Context context, ForStatementNode node ) throws Exception {
if( true || debug ) {
Debugger.trace("evaluating ForStatementNode = " + node);
}
node.block = context.getBlock();
context.exitBlock(node);
context.enterBlock(node.statement);
node.statement.evaluate(context,this);
context.exitBlock(node.statement.last());
return UndefinedValue.undefinedValue;
}
/**
* ForInStatementNode
*
* { property, object, statement }
*
* Semantics:
* 1 Tag node with current block label.
* 2 Evaluate statements.
* 3 Exit the current block.
* 4 Return.
*/
Value evaluate( Context context, ForInStatementNode node ) throws Exception {
if( true || debug ) {
Debugger.trace("evaluating ForInStatementNode = " + node);
}
node.block = context.getBlock();
context.exitBlock(node);
context.enterBlock(node.statement);
node.statement.evaluate(context,this);
context.exitBlock(node.statement.last());
return UndefinedValue.undefinedValue;
}
/**
* WithStatementNode
*
* Syntax:
* { expr, statement }
*
* Semantics:
* 1. Tag node with current block label.
* 4. Evaluate statement.
* 5. Return.
*/
Value evaluate( Context context, WithStatementNode node ) throws Exception {
if( debug ) {
Debugger.trace("evaluating WithStatementNode = " + node);
}
node.block = context.getBlock();
node.statement.evaluate(context,this);
return UndefinedValue.undefinedValue;
}
/**
* BreakStatementNode
*
* Semantics:
* 1. Tag node with current block label.
* 2. Exit the current block.
* 3. Return.
*/
Value evaluate( Context context, BreakStatementNode node ) throws Exception {
if( debug ) {
Debugger.trace("defining BreakStatementNode = " + node);
}
// Point the current statement to its block.
// This reference will be used to compute dominators.
node.block = context.getBlock();
context.exitBlock(node);
return UndefinedValue.undefinedValue;
}
/**
* ContinueStatementNode
*
* Semantics:
* 1. Tag node with current block label.
* 2. Exit the current block.
* 3. Return.
*/
Value evaluate( Context context, ContinueStatementNode node ) throws Exception {
if( debug ) {
Debugger.trace("defining ContinueStatementNode = " + node);
}
// Point the current statement to its block.
// This reference will be used to compute dominators.
node.block = context.getBlock();
context.exitBlock(node);
return UndefinedValue.undefinedValue;
}
/**
* ReturnStatementNode
*
* Semantics:
* 1. Tag node with current block label.
* 2. Exit the current block.
* 3. Return.
*/
Value evaluate( Context context, ReturnStatementNode node ) throws Exception {
if( debug ) {
Debugger.trace("defining ReturnStatementNode = " + node);
}
node.block = context.getBlock();
context.exitBlock(node);
return UndefinedValue.undefinedValue;
}
/**
* ThrowStatementNode
*
* Semantics:
* 1. Tag node with current block label.
* 2. Exit the current block.
* 3. Return.
*/
Value evaluate( Context context, ThrowStatementNode node ) throws Exception {
if( debug ) {
Debugger.trace("defining ThrowStatementNode = " + node);
}
node.block = context.getBlock();
context.exitBlock(node);
return UndefinedValue.undefinedValue;
}
/**
* TryStatementNode
* { tryblock, catchlist, finallyblock }
*
* Semantics:
* 1. Tag node with current block label.
* 4. Evaluate the tryblock.
* 5. Exit the current block.
* 7. Evaluate the catchblock.
* 8. Exit the current block.
* 9. Evaluate the finally block.
* 10. Exit the current block.
* 11. Return.
*/
Value evaluate( Context context, TryStatementNode node ) throws Exception {
if( debug ) {
Debugger.trace("evaluating Node = " + node);
}
node.block = context.getBlock();
node.tryblock.evaluate(context,this);
context.exitBlock(node.tryblock.last());
if( node.catchlist!=null ) {
node.catchlist.evaluate(context,this);
context.exitBlock(node.catchlist.last());
}
if( node.finallyblock!=null ) {
context.enterBlock(node.finallyblock);
node.finallyblock.evaluate(context,this);
context.exitBlock(node.finallyblock.last());
}
return UndefinedValue.undefinedValue;
}
/**
* CatchClauseNode
*
* Syntax:
* { parameter statements }
*
* Semantics:
* 1. Tag node with current block label.
* 2. Evaluate statements.
* 3. Return.
*/
Value evaluate( Context context, CatchClauseNode node ) throws Exception {
if( debug ) {
Debugger.trace("evaluating CatchClauseNode = " + node);
}
node.block = context.getBlock();
node.statements.evaluate(context,this);
return UndefinedValue.undefinedValue;
}
/**
* FinallyClauseNode
*
* Syntax:
* { statements }
*
* Semantics:
* 1. Tag node with current block label.
* 2. Evaluate statements.
* 3. Return.
*/
Value evaluate( Context context, FinallyClauseNode node ) throws Exception {
if( debug ) {
Debugger.trace("evaluating FinallyClauseNode = " + node);
}
node.block = context.getBlock();
node.statements.evaluate(context,this);
return UndefinedValue.undefinedValue;
}
// Definitions
/**
* namespaces is used to store namespace attributes for the
* current definition being evaluated.
*/
private Vector namespaces = new Vector();
private Vector parameters = new Vector();
/**
* AnnotatedDefinition
*/
public Value evaluate( Context context, AnnotatedDefinitionNode node ) throws Exception {
if( debug ) {
Debugger.trace( "defining AnnotatedDefinitionNode: " + node );
}
node.block = context.getBlock();
Scope local = context.getLocal();
if( node.definition != null ) {
node.definition.evaluate(context,this);
}
return UndefinedValue.undefinedValue;
}
static final void testAnnotatedDefinition() throws Exception {
String[] input = {
"",
};
String[] expected = {
"",
};
testEvaluator("AnnotatedDefinition",input,expected);
}
/**
* ExportDefinition
*/
public Value evaluate( Context context, ExportDefinitionNode node ) throws Exception {
if( debug ) {
Debugger.trace( "defining ExportDefinitionNode: " + node );
}
node.block = context.getBlock();
return UndefinedValue.undefinedValue;
}
static final void testExportDefinition() throws Exception {
String[] input = {
"",
};
String[] expected = {
"",
};
testEvaluator("ExportDefinition",input,expected);
}
/**
* VariableDefinition
*/
public Value evaluate( Context context, VariableDefinitionNode node ) throws Exception {
if( debug ) {
Debugger.trace( "defining VariableDefinitionNode: " + node );
}
node.block = context.getBlock();
return UndefinedValue.undefinedValue;
}
static final void testVariableDefinition() throws Exception {
String[] input = {
"var x; x;",
"var y:T; y;",
"class C; class C{}; var x, y:C; y;",
"var x = 1; const y = 2; var z = n;",
"var x = 1,y = 2,z = n;",
"if(true) {const n = 1;} const z = n;",
};
String[] expected = {
"code(expressionstatement( identifier( x ) ))",
"error(Type expression does not evaluate to a type: undefined)",
"code(expressionstatement( identifier( y ) ))",
"",
"",
"",
};
testEvaluator("VariableDefinition",input,expected);
}
/**
* FunctionDeclaration
*/
public Value evaluate( Context context, FunctionDeclarationNode node ) throws Exception {
if( debug ) {
Debugger.trace( "defining FunctionDeclarationNode: " + node );
}
node.block = context.getBlock();
return UndefinedValue.undefinedValue;
}
static final void testFunctionDeclaration() throws Exception {
String[] input = {
"function f(); f;",
"function f(x); f;",
"function f(x:Integer,y:String); f;",
};
String[] expected = {
"completion( 0, object(function(f)){object(namespace(_parameters_)){}=object(namespace(object(namespace(_parameters_)){})){_result_={ 0, typevalue(any){}, undefined }}}, null )",
"completion( 0, object(function(f)){object(namespace(_parameters_)){}=object(namespace(object(namespace(_parameters_)){})){x={ 0, typevalue(any){}, undefined }, _result_={ 0, typevalue(any){}, undefined }}}, null )",
"completion( 0, object(function(f)){object(namespace(_parameters_)){}=object(namespace(object(namespace(_parameters_)){})){x={ 0, typevalue(integer){}, undefined }, _result_={ 0, typevalue(any){}, undefined }, y={ 0, typevalue(string){}, undefined }}}, null )",
};
testEvaluator("FunctionDeclaration",input,expected);
}
/**
* FunctionDefinition
*/
public Value evaluate( Context context, FunctionDefinitionNode node ) throws Exception {
if( debug ) {
Debugger.trace( "defining FunctionDefinitionNode: " + node );
}
node.block = context.getBlock();
context.exitBlock(node.decl);
if( node.body!=null) {
node.body.first().markLeader();
node.body.evaluate(context,this);
context.exitBlock(node.body.last());
}
return UndefinedValue.undefinedValue;
}
static final void testFunctionDefinition() throws Exception {
String[] input = {
"function f(){}; f",
"function f(x){var a;}; f",
"namespace V; const v=namespace(V);v function f(x,y){var a; const b;}; v::f",
};
String[] expected = {
"completion( 0, object(function(f)){object(namespace(_parameters_)){}=object(namespace(object(namespace(_parameters_)){})){_result_={ 0, typevalue(any){}, undefined }}}, null )",
"completion( 0, object(function(f)){a={ 0, typevalue(any){}, undefined }, object(namespace(_parameters_)){}=object(namespace(object(namespace(_parameters_)){})){x={ 0, typevalue(any){}, undefined }, _result_={ 0, typevalue(any){}, undefined }}, _code_={ 0, any, list([list([])]) }}, null )",
"",
};
testEvaluator("FunctionDefinition",input,expected);
}
/**
* ClassDeclaration
*/
public Value evaluate( Context context, ClassDeclarationNode node ) throws Exception {
if( debug ) {
Debugger.trace( "defining ClassDeclarationNode: " + node );
}
node.block = context.getBlock();
return UndefinedValue.undefinedValue;
}
static final void testClassDeclaration() throws Exception {
String[] input = {
"class C; C;"
};
String[] expected = {
"completion( 0, typevalue(class(C extends null)){}, null )"
};
testEvaluator("ClassDeclaration",input,expected);
}
/**
* ClassDefinition
*
* 1. Create a new class object.
* 2. Add the classname and object to the global type database.
* 3. Push the class object onto the scope stack.
*/
public Value evaluate( Context context, ClassDefinitionNode node ) throws Exception {
if( debug ) {
Debugger.trace( "defining ClassDefinitionNode: " + node );
}
node.block = context.getBlock();
if( node.statements!=null ) {
node.statements.evaluate(context,this);
}
return UndefinedValue.undefinedValue;
}
static final void testClassDefinition() throws Exception {
String[] input = {
"class C {} C",
};
String[] expected = {
"completion( 0, typevalue(class(C extends null)){}, null )",
};
testEvaluator("ClassDefinition",input,expected);
}
/**
* NamespaceDefinition
*/
public Value evaluate( Context context, NamespaceDefinitionNode node ) throws Exception {
if( debug ) {
Debugger.trace( "defining NamespaceDefinitionNode: " + node );
}
node.block = context.getBlock();
return UndefinedValue.undefinedValue;
}
static final void testNamespaceDefinition() throws Exception {
String[] input = {
"namespace N; N;",
"namespace N2 extends N1; N2;",
};
String[] expected = {
"completion( 0, object(namespace(N)){}, null )",
"completion( 0, object(namespace(N2)){}, null )",
};
testEvaluator("NamespaceDefinition",input,expected);
}
/**
* Program
*/
public Value evaluate( Context context, ProgramNode node ) throws Exception {
if( debug ) {
Debugger.trace( "defining ProgramNode: " + node );
}
if( node.statements != null ) {
node.statements.first().markLeader();
node.statements.evaluate(context,this);
context.exitBlock(node.statements.last());
}
return UndefinedValue.undefinedValue;
}
/**
* Main. Runs self diagnostics.
*/
static int failureCount = 0;
public static void main( String[] args ) {
PrintStream outfile = null;
try {
outfile = new PrintStream( new FileOutputStream( "Parser.test" ) );
System.setOut( outfile );
Debugger.trace( "Parser test begin" );
if( failureCount != 0 )
Debugger.trace( "DefinitionEvaluator test completed: " + failureCount + " tests failed" );
else
Debugger.trace( "DefinitionEvaluator test completed successfully" );
}
catch( Exception e ) {
//Debugger.trace( "compile error: " + e );
e.printStackTrace();
}
finally {
outfile.close();
System.setOut( null );
}
}
static final void testEvaluator(String name, String[] input, String[] expected) throws Exception {
Debugger.trace( "begin testEvaluator: " + name );
String result = "";
Node node;
Value type;
Evaluator evaluator;
Class pc = Parser.class;
Class[] args = new Class[0];
Parser parser;
long t=0;
ObjectValue global = null;
for( int i = 0; i < input.length; i++ ) {
Context context = new Context();
try {
global = new ObjectValue("__systemGlobal", new GlobalObject());
context.enterClass(global);
parser = new Parser(new StringReader(input[i]));
evaluator = new BlockEvaluator();
System.gc();
t = System.currentTimeMillis();
node = parser.parseProgram();
Debugger.trace(" I: "+global);
context.evaluator = evaluator;
node.evaluate(context, evaluator);
Debugger.trace(" D: "+global);
t = System.currentTimeMillis() - t;
context.exitClass();
} catch( Exception x ) {
x.printStackTrace();
t = System.currentTimeMillis() - t;
result = "error("+x.getMessage()+")";
context.exitClass();
}
if( result.equals( expected[i] ) ) {
Debugger.trace( " " + i + " passed in " + Long.toString(t) +
" msec [" + input[i] + "] = " + result );
} else {
failureCount++;
Debugger.trace( " " + i + " failed [" + input[i] + "] = " + result );
}
}
Debugger.trace( "finish testEvaluator: " + name );
}
}
/*
* The end.
*/

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,56 @@
package com.compilercompany.es3c.v1;
import java.util.Enumeration;
/**
* class ArrayType
*/
public final class ArrayType extends ObjectType implements Type {
boolean debug = false;
public static final TypeValue type = new TypeValue(new ArrayType());
public String toString() {
return "array";
}
private ArrayType() {
super("array");
ObjectType.type.addSub(this);
}
/**
* Type methods
*/
public Value convert(Context context, Value value) throws Exception {
if( value instanceof ListValue ) {
return this.convert(context,(ListValue)value);
} else {
return value;
}
}
public Value convert(Context context, ListValue value) throws Exception {
Value array = new ObjectValue(this);
Enumeration e = value.elements();
int i = 0;
while(e.hasMoreElements()) {
Slot slot;
String name;
Value elem;
name = ""+i;
slot = array.add(null,name);
elem = (Value) e.nextElement();
slot.value = elem.getValue(context);
i++;
}
return array;
}
}
/*
* The end.
*/

View File

@@ -0,0 +1,26 @@
package com.compilercompany.es3c.v1;
/**
* class BooleanType
*/
public final class BooleanType extends ObjectType implements Type {
private static final boolean debug = false;
public static final TypeValue type = new TypeValue(new BooleanType());
public String toString() {
return "boolean";
}
private BooleanType() {
super("boolean");
ObjectType.type.addSub(this);
}
}
/*
* The end.
*/

View File

@@ -0,0 +1,26 @@
package com.compilercompany.es3c.v1;
/**
* class CharacterType
*/
public final class CharacterType extends ObjectType implements Type {
boolean debug = false;
public static final TypeValue type = new TypeValue(new CharacterType());
public String toString() {
return "character";
}
private CharacterType() {
super("character");
ObjectType.type.addSub(this);
}
}
/*
* The end.
*/

View File

@@ -0,0 +1,53 @@
package com.compilercompany.es3c.v1;
import java.util.Vector;
/**
* class ClassType
*/
public final class ClassType extends ObjectType implements Type {
private static final boolean debug = false;
public static final TypeValue type = new TypeValue(new ClassType());
String name = "";
public String toString() {
return "class("+name+" extends " + superType + ")";
}
public ClassType(String name) {
super("class#"+name);
this.name = name;
ClassType.type.addSub(this);
}
private ClassType() {
super("class");
ObjectType.type.addSub(this);
}
private Type superType;
public void setSuper(Type type) {
superType = type;
superType.addSub(this);
}
public Type getSuper() {
return superType;
}
/**
* Init
*/
public void init( Value ob ) {
ob.type = TypeType.type;
}
}
/*
* The end.
*/

View File

@@ -0,0 +1,21 @@
package com.compilercompany.es3c.v1;
/**
* class CompletionType
*/
public final class CompletionType extends ObjectType {
public static final int normalType = 0x00;
public static final int breakType = 0x01;
public static final int continueType = 0x02;
public static final int returnType = 0x03;
public static final int throwType = 0x04;
CompletionType() {
super("completion");
}
}
/*
* The end.
*/

View File

@@ -0,0 +1,34 @@
package com.compilercompany.es3c.v1;
/**
* class FunctionType
*/
public final class FunctionType extends ObjectType implements Type {
boolean debug = false;
public static final TypeValue type = new TypeValue(new FunctionType());
String name;
public String toString() {
return "function("+name+")";
}
public FunctionType(String name) {
super("function");
this.name = name;
FunctionType.type.addSub(this);
}
private FunctionType() {
super("function");
ObjectType.type.addSub(this);
}
}
/*
* The end.
*/

View File

@@ -0,0 +1,26 @@
package com.compilercompany.es3c.v1;
/**
* class IntegerType
*/
public final class IntegerType extends ObjectType implements Type {
boolean debug = false;
public static final TypeValue type = new TypeValue(new IntegerType());
public String toString() {
return "integer";
}
private IntegerType() {
super("integer");
ObjectType.type.addSub(this);
}
}
/*
* The end.
*/

View File

@@ -0,0 +1,38 @@
package com.compilercompany.es3c.v1;
/**
* class NamespaceType
*/
public final class NamespaceType extends ObjectType implements Type {
boolean debug = false;
public static final TypeValue type = new TypeValue(new NamespaceType());
public String toString() {
if( name == null ) {
return "namespace";
} else {
return "namespace("+name+")";
}
}
private String name;
public NamespaceType(String name) {
super("namespace");
this.name = name;
NamespaceType.type.addSub(this);
}
private NamespaceType() {
super("namespace");
ObjectType.type.addSub(this);
}
}
/*
* The end.
*/

View File

@@ -0,0 +1,26 @@
package com.compilercompany.es3c.v1;
/**
* class NoneType
*/
public final class NoneType extends ObjectType implements Type {
private static final boolean debug = false;
public static final TypeValue type = new TypeValue(new NoneType());
public String toString() {
return "none";
}
private NoneType() {
super("none");
ObjectType.type.addSub(this);
}
}
/*
* The end.
*/

View File

@@ -0,0 +1,26 @@
package com.compilercompany.es3c.v1;
/**
* class NullType
*/
public final class NullType extends ObjectType implements Type {
boolean debug = false;
public static final TypeValue type = new TypeValue(new NullType());
public String toString() {
return "null";
}
private NullType() {
super("null");
ObjectType.type.addSub(this);
}
}
/*
* The end.
*/

View File

@@ -0,0 +1,43 @@
package com.compilercompany.es3c.v1;
/**
* class NumberType
*/
public final class NumberType extends ObjectType implements Type {
boolean debug = false;
public static final TypeValue type = new TypeValue(new NumberType());
public String toString() {
return "number";
}
private NumberType() {
super("number");
ObjectType.type.addSub(this);
}
/**
* Type methods
*/
public void init( Value ob ) throws Exception {
if( debug ) {
Debugger.trace("NumberType.init() with ob = " + ob );
}
Slot slot;
slot = ob.add(null,"Number");
slot.type = FunctionType.type;
slot.value = new ObjectValue(new FunctionType("constructor"));
slot.value.type = NumberType.type;
}
}
/*
* The end.
*/

View File

@@ -0,0 +1,209 @@
package com.compilercompany.es3c.v1;
import java.util.Vector;
/**
* class ObjectType
*/
public class ObjectType implements Type {
private static final boolean debug = true;
public static final TypeValue type = new TypeValue(new ObjectType());
String name = "object";
public String toString() {
return name;
}
public ObjectType(String name) {
this.name = name;
ObjectType.type.addSub(this);
}
private ObjectType() {
}
/**
* Type methods
*/
/**
* Init
*/
public void init( Value ob ) throws Exception {
}
private Vector values_ = new Vector();
private Type[] converts_ = null;
public Type[] converts() {
if( converts_ == null) {
converts_ = new Type[6];
converts_[0] = UndefinedType.type;
converts_[1] = NullType.type;
converts_[2] = BooleanType.type;
converts_[3] = NumberType.type;
converts_[4] = StringType.type;
converts_[5] = ObjectType.type;
}
return converts_;
}
public void addSub(Type type) {
if( debug ) {
Debugger.trace("ObjectType.addSub() type = " + type + " to " + this);
}
values_.addElement(type);
}
public Object[] values() {
Object[] values = new Object[values_.size()];
values_.copyInto(values);
return values;
}
public Value convert(Context context, Value value) throws Exception {
return value;
}
public Value coerce(Context context, Value value) {
return value;
}
private Type superType;
public void setSuper(Type type) {
superType = type;
}
public Type getSuper() {
return superType;
}
public boolean includes(Value value) {
if( debug ) {
Debugger.trace("ObjectType.includes() with this = " + this + ", value.type = " + value.type + ", values_ = " + values_);
}
return values_.contains(value.type);
}
/**
* subset
*
* return t2 if t2 is a proper subset of t1, otherwise
* return null.
*/
public static Type subset(Type t1, Type t2) {
if(debug) {
Debugger.trace("subset() with t1 = " + t1 + ", t2 = " + t2 );
}
Object[] v1 = t1.values();
Object[] v2 = t2.values();
int l1 = v1.length;
int l2 = v2.length;
int i1;
int i2;
for(i2 = 0; i2 < l2; i2++) {
// For each value in t2, check that it is also in t1.
for(i1 = 0; i1 < l1; i1++) {
if(debug) {
Debugger.trace("subset() matching " + v2[i2] + " = " + v1[i1] );
}
// If the match is found, then break out of this
// inner loop and continue checking values.
if(v1[i1]==v2[i2]) {
if(debug) {
Debugger.trace("value found");
}
break;
}
}
// Not a subset if we got to the end of the t1 value array
// without finding the current t2 value.
if(i1==l1) {
return null;
}
}
// If we got to the end of the t2 values, then t2 is a subset
// of t1. Return t2.
if(i2==l2) {
return t2;
}
return null;
}
public static Type subset(Type[] at1, Type t2) {
if( at1 == null ) {
return null;
}
// Check that the values of t2 are a subset of values
// of at least one of the types of the ta1 array.
int l = at1.length;
int i;
for( i = 0; i < l; i++ ) {
if( subset(at1[i],t2) != null ) {
return at1[i];
}
}
return null;
}
/**
* intersection
*
* return the aggregate type that represents the intersection
* of t1 and t2. The empty set is expressed as null.
*/
public static Type intersection(Type t1, Type t2) {
// Return a type that represents the intersection
// of values in both t1 and t2.
/*
for(;;) {
for(;;) {
}
}
*/
return null;
}
public static Type intersection(Type[] ts1, Type t2) {
return null;
}
}
/*
* The end.
*/

View File

@@ -0,0 +1,41 @@
package com.compilercompany.es3c.v1;
/**
* class RegExpType
*/
public final class RegExpType extends ObjectType implements Type {
boolean debug = false;
public static final RegExpType type = new RegExpType();
String expr;
public String toString() {
return "regexp("+expr+")";
}
private RegExpType() {
super("regexp");
ObjectType.type.addSub(this);
}
public RegExpType(String expr) {
super("regexp");
this.expr = expr;
// Make this type a subtype of the base RegExpType.
// This means that RegExpType.type.includes(this)
// is true. Since values created by this type have
// this type as their type, for any reg exp value
// RegExpType.type.includes(value.type) is true.
RegExpType.type.addSub(this);
}
}
/*
* The end.
*/

View File

@@ -0,0 +1,26 @@
package com.compilercompany.es3c.v1;
/**
* class StringType
*/
public final class StringType extends ObjectType implements Type {
boolean debug = false;
public static final TypeValue type = new TypeValue(new StringType());
public String toString() {
return "string";
}
private StringType() {
super("string");
ObjectType.type.addSub(this);
}
}
/*
* The end.
*/

View File

@@ -0,0 +1,39 @@
package com.compilercompany.es3c.v1;
/**
* class TypeType
*/
public class TypeType extends ObjectType implements Type {
boolean debug = false;
public static TypeValue type = new TypeValue();
public String toString() {
return "type";
}
public TypeType() {
super("type");
ObjectType.type.addSub(this);
}
public boolean includes(Value value) {
// A type is always a member of itself.
if(value.type==TypeType.type) {
return true;
}
// Check the store in the base object.
return super.includes(value);
}
}
/*
* The end.
*/

View File

@@ -0,0 +1,25 @@
package com.compilercompany.es3c.v1;
/**
* class UndefinedType
*/
public final class UndefinedType extends ObjectType implements Type {
boolean debug = false;
public static final TypeValue type = new TypeValue(new UndefinedType());
public String toString() {
return "undefined";
}
private UndefinedType() {
super("undefined");
ObjectType.type.addSub(this);
}
}
/*
* The end.
*/

View File

@@ -0,0 +1,51 @@
package com.compilercompany.es3c.v1;
/**
* A boolean value: true or false.
*/
public class BooleanValue extends ObjectValue {
private static final boolean debug = false;
public static final Value trueValue = new BooleanValue(true);
public static final Value falseValue = new BooleanValue(false);
boolean value;
public String toString() {
return "boolean("+value+")";
}
BooleanValue(boolean value) {
this.value = value;
this.type = BooleanType.type;
}
BooleanValue(boolean value, Value type) {
this.value = value;
this.type = type;
}
/**
* Return a value of the currently specified type.
*/
public Value getValue(Context context) throws Exception {
Value value;
if(type == BooleanType.type) {
value = this;
} else {
value = ((TypeValue)type).convert(context,this);
}
return value;
}
}
/*
* The end.
*/

View File

@@ -0,0 +1,44 @@
package com.compilercompany.es3c.v1;
/**
* A character value.
*/
public class CharacterValue extends ObjectValue {
private static final boolean debug = false;
public String toString() {
return "character("+value+")";
}
char value;
CharacterValue(char value) {
this.type = CharacterType.type;
this.value = value;
}
CharacterValue(char value, Value type) {
this.type = type;
this.value = value;
}
public Value getValue(Context context) throws Exception {
Value value;
if(type == CharacterType.type) {
value = this;
} else {
throw new Exception("Unexpected type of character value.");
}
return value;
}
}
/*
* The end.
*/

View File

@@ -0,0 +1,40 @@
package com.compilercompany.es3c.v1;
import java.util.Vector;
/**
* A code value (intermediate).
*
* This value holds the intermediate code for an non-constant value.
*/
public class CodeValue extends Value {
private static final boolean debug = false;
private Node node;
public CodeValue( Node node ) {
this.node = node;
}
public String toString() {
return "code("+node+")";
}
/**
* The result depends on during what phase this function
* is called. At compile time it will either return itself,
* or a compile-time constant value. At runtime it will
* return a runtime value.
*/
public Value getValue(Context context) throws Exception {
// ACTION: execute the code to get the value.
return node.evaluate(context,context.evaluator);
}
}
/*
* The end.
*/

View File

@@ -0,0 +1,33 @@
package com.compilercompany.es3c.v1;
/**
* A completion value (intermediate).
*/
public class CompletionValue extends Value {
private static final boolean debug = false;
int type;
Value value;
String target;
public CompletionValue(int type, Value value, String target) {
this.type = type;
this.value = value;
this.target = target;
}
public CompletionValue () {
this(CompletionType.normalType,NullValue.nullValue,"");
}
public String toString() {
return "completion( "+type+", "+value+", "+target+" )";
}
}
/*
* The end.
*/

View File

@@ -0,0 +1,184 @@
package com.compilercompany.es3c.v1;
/**
* The global object initializer.
*
* An instance of this class is used to initialize a global
* object.
*/
public final class GlobalObject implements Init {
/**
* Init
*/
public void init( Value ob ) throws Exception {
// Add slots for pre-defined types. A note on values
// and types: Each type contains a set of values. A
// value is an instance of the value class. For example,
// new BooleanValue(true) is the true value of the boolean
// type. BooleanValue.type is the type of all boolean
// values. Value classes implement the Value interface.
Slot slot;
// Types
slot = ob.add(null,"none");
slot.type = TypeType.type;
slot.value = NoneType.type;
slot = ob.add(null,"void");
slot.type = TypeType.type;
slot.value = UndefinedType.type;
slot = ob.add(null,"Null");
slot.type = TypeType.type;
slot.value = NullType.type;
slot = ob.add(null,"Boolean");
slot.type = TypeType.type;
slot.value = BooleanType.type;
slot = ob.add(null,"Integer");
slot.type = TypeType.type;
slot.value = IntegerType.type;
slot = ob.add(null,"Number");
slot.type = TypeType.type;
slot.value = NumberType.type;
slot = ob.add(null,"Character");
slot.type = TypeType.type;
slot.value = CharacterType.type;
slot = ob.add(null,"String");
slot.type = TypeType.type;
slot.value = StringType.type;
slot = ob.add(null,"Function");
slot.type = TypeType.type;
slot.value = FunctionType.type;
slot = ob.add(null,"Array");
slot.type = TypeType.type;
slot.value = ArrayType.type;
slot = ob.add(null,"Type");
slot.type = TypeType.type;
slot.value = TypeType.type;
slot = ob.add(null,"Unit");
slot.type = ObjectType.type;
slot.value = new ObjectValue();
// Attributes
slot = ob.add(null,"local");
slot.type = ObjectType.type;
slot.value = new ObjectValue();
slot = ob.add(null,"regional");
slot.type = ObjectType.type;
slot.value = new ObjectValue();
slot = ob.add(null,"global");
slot.type = ObjectType.type;
slot.value = new ObjectValue();
slot = ob.add(null,"extend");
slot.type = ObjectType.type;
slot.value = new ObjectValue();
slot = ob.add(null,"unit");
slot.type = ObjectType.type;
slot.value = new ObjectValue();
slot = ob.add(null,"public");
slot.type = NamespaceType.type;
slot.value = new ObjectValue(new NamespaceType("public"));
slot = ob.add(null,"internal");
slot.type = NamespaceType.type;
slot.value = new ObjectValue(new NamespaceType("internal"));
slot = ob.add(null,"private");
slot.type = NamespaceType.type;
slot.value = new ObjectValue(new NamespaceType("private"));
slot = ob.add(null,"implicit");
slot.type = ObjectType.type;
slot.value = new ObjectValue();
slot = ob.add(null,"explicit");
slot.type = ObjectType.type;
slot.value = new ObjectValue();
slot = ob.add(null,"indexable");
slot.type = ObjectType.type;
slot.value = new ObjectValue();
slot = ob.add(null,"nonindexable");
slot.type = ObjectType.type;
slot.value = new ObjectValue();
slot = ob.add(null,"final");
slot.type = ObjectType.type;
slot.value = new ObjectValue();
slot = ob.add(null,"dynamic");
slot.type = ObjectType.type;
slot.value = new ObjectValue();
slot = ob.add(null,"fixed");
slot.type = ObjectType.type;
slot.value = new ObjectValue();
slot = ob.add(null,"static");
slot.type = ObjectType.type;
slot.value = new ObjectValue();
slot = ob.add(null,"constructor");
slot.type = ObjectType.type;
slot.value = new ObjectValue();
slot = ob.add(null,"abstract");
slot.type = ObjectType.type;
slot.value = new ObjectValue();
slot = ob.add(null,"virtual");
slot.type = ObjectType.type;
slot.value = new ObjectValue();
slot = ob.add(null,"final");
slot.type = ObjectType.type;
slot.value = new ObjectValue();
slot = ob.add(null,"override");
slot.type = ObjectType.type;
slot.value = new ObjectValue();
slot = ob.add(null,"mayOverride");
slot.type = ObjectType.type;
slot.value = new ObjectValue();
slot = ob.add(null,"prototype");
slot.type = ObjectType.type;
slot.value = new ObjectValue();
slot = ob.add(null,"weak");
slot.type = ObjectType.type;
slot.value = new ObjectValue();
slot = ob.add(null,"unused");
slot.type = ObjectType.type;
slot.value = new ObjectValue();
}
}
/*
* The end.
*/

View File

@@ -0,0 +1,58 @@
package com.compilercompany.es3c.v1;
import java.util.Vector;
import java.util.Enumeration;
/**
* A list value (intermediate).
*/
public class ListValue extends ObjectValue {
private static final boolean debug = false;
Vector data = new Vector();
int size() {
return data.size();
}
Enumeration elements() {
return data.elements();
}
public String toString() {
return "list(" + data + ")";
}
public ListValue push(Object item) {
data.addElement(item);
return this;
}
public Value getValue(Context context) throws Exception {
int size = data.size();
if( size > 0 ) {
return ((Value) data.elementAt(size-1)).getValue(context);
}
return UndefinedValue.undefinedValue;
}
public Value getValue(Context context, int n) throws Exception {
int size = data.size();
if( n >= 0 && n < size ) {
return ((Value) data.elementAt(n)).getValue(context);
}
return UndefinedValue.undefinedValue;
}
public void pop() {
int size = data.size();
if( size > 0 ) {
data.setSize(size-1);
}
}
}
/*
* The end.
*/

Some files were not shown because too many files have changed in this diff Show More