How to represent classes in a tree-based abstract parser

I read related questions, but none of them seem to directly address the issue. I am working on writing a PHP interpreter script. I have an AST generating the correct nodes for everything except classes. Class handling is slightly different from processing functions, so I'm looking for how to process classes that are autonomous and that extend other classes.

I looked at ANTLR, but I can not afford the overhead, as this is for an embedded platform. What I'm looking for is a concept conceptually behind classes in AST so that they can be executed by the performing part of the interpreter. Good links with specific answers to this question are definitely appreciated.

+5
source share
5 answers

ANTLR is more or less irrelevant to your problem.

A class in PHP is basically a map from strings to attributes. Each attribute can be open, closed, protected. Each attribute also contains a value, which can be a static variable or method. Methods are functions that (in PHP) take an implicit $ this parameter. So you can think of the class as basically a fancy array object in PHP.

When you create an object, you point it to a pointer to your object in the PHP class. When you call a method on this object, you are viewing the method through an object of the class that you get through this pointer.

, .

+2

, , ? PHP, , , , . AST, ANTLR, , .

+1

, , - , , , .

, , , node.

0

I would suggest using JavaCC (or fork FreeCC) to parse and build your AST. JavaCC generates a parser that has no runtime dependencies. It's hard to write a smaller / faster parser than the code that JavaCC generates.

0
source

Take a look at phc abstract grammar , it does just that. (By the way, it seems that using phc front-end might be better than reinventing the wheel).

Class_def ::= Class_mod CLASS_NAME extends:CLASS_NAME? implements:INTERFACE_NAME* Member* ;
Class_mod ::= "abstract"? "final"? ;

Interface_def ::= INTERFACE_NAME extends:INTERFACE_NAME* Member* ;

Member ::= Method | Attribute ;

Method ::= Signature Statement*? ;
Signature ::= Method_mod is_ref:"&"? METHOD_NAME Formal_parameter* ;
Method_mod ::= "public"? "protected"? "private"? "static"? "abstract"? "final"? ;
Formal_parameter ::= Type is_ref:"&"? var:Name_with_default ;
Formal_parameter ::= Type is_ref:"&"? var:Name_with_default ;
Type ::= CLASS_NAME? ;
Name_with_default ::= VARIABLE_NAME Expr? ;

Attribute ::= Attr_mod vars:Name_with_default* ;
Attr_mod ::= "public"? "protected"? "private"? "static"? "const"?  ;
0
source

All Articles