Skip to content

Getting started

Hadron67 edited this page Feb 22, 2018 · 1 revision

Anyway, install tscc-compiler first

npm install tscc-compiler -g

A simple example

Let's begin with a simple example of a parser that accepts an array of integers like this:

[ 65, 897, 45, 987 ]

Create a file test.y and edit it with an editor of your choice. Enter the following code:

%output "javascript"
%lex {
	< [' ', '\n', '\r']+ >: [='']
    
    < NUM: ['0'-'9']+ >: { $$ = $token.val; }
    < BRA: '[' >
    < KET: ']' >
    < COMMA: ',' >
}
%%
start: '[' array ']';
array: nonEmptyArray |;
nonEmptyArray: 
	nonEmptyArray ',' n = <NUM> { console.log("I saw a number " + n); }
|	n = <NUM> { console.log("I saw a number " + n); }
;
%%
var parser = createParser();
parser.init();
parser.accept(process.argv[2]);
parser.end();

now type the following command in your terminal:

tscc-compiler test.y

file test.js and test.output will be generated. You can test the parser with the following command:

node test.js "[89, 654897, 8745]"

and you should get

I saw a number 89
I saw a number 654897
I saw a number 8745

Handle errors

You may have discovered even if you give an invalid input, everything seems fine, that is because we have not handled the errors yet.

Now modify the last four lines of test.y:

var parser = createParser();
parser.on('lexicalerror', function(chr, line, column){
    console.log(`lexical error at line ${line + 1}, column ${column + 1}`);
    parser.halt();
});
parser.on('syntaxerror', function(msg, token){
    console.log(`syntax error at line ${token.startLine + 1}, column ${token.startColumn + 1}: ${msg}`);
    parser.halt();
});
parser.init();
parser.accept(process.argv[2]);
parser.end();

the parser uses event callbacks to handle errors, and in the two callbacks we first print error message and then call parser.halt() to stop the parser, otherwise it will ignore the error and continue to parse.

You can try giving the parser an invalid input to see what will happen:

node test.js "[1,2,3,,5]"

More examples

You can checkout more examples at directory examples/ in the source code.

Clone this wiki locally