This repository has been archived by the owner on Jun 4, 2019. It is now read-only.
/
ast_php.mli.nw
1935 lines (1575 loc) · 54.7 KB
/
ast_php.mli.nw
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
% also contains type_php.mli and scope_php.mli
\section{Overview}
\subsection{[[ast_php.mli]] structure}
The [[Ast_php]] module defines all the types and constructors used to
represent PHP code (the Abstract Syntax Tree of PHP). Any user of
\pfff must thus understand and know those types as any code using the
\pfff API will probably need to do some pattern matching over
those types.
\l if dont remember, can use -dump_php to refresh memory
Here is the toplevel structure of the [[Ast_php]] module:
<<ast_php.mli>>=
open Common
(*****************************************************************************)
(* The AST related types *)
(*****************************************************************************)
(* ------------------------------------------------------------------------- *)
(* Token/info *)
(* ------------------------------------------------------------------------- *)
<<AST info>>
(* ------------------------------------------------------------------------- *)
(* Name *)
(* ------------------------------------------------------------------------- *)
<<AST name>>
(* ------------------------------------------------------------------------- *)
(* Type *)
(* ------------------------------------------------------------------------- *)
<<AST type>>
(* ------------------------------------------------------------------------- *)
(* Expression *)
(* ------------------------------------------------------------------------- *)
<<AST expression>>
(* ------------------------------------------------------------------------- *)
(* Expression bis, lvalue *)
(* ------------------------------------------------------------------------- *)
<<AST lvalue>>
(* ------------------------------------------------------------------------- *)
(* Statement *)
(* ------------------------------------------------------------------------- *)
<<AST statement>>
(* ------------------------------------------------------------------------- *)
(* Function definition *)
(* ------------------------------------------------------------------------- *)
<<AST function definition>>
<<AST lambda definition>>
(* ------------------------------------------------------------------------- *)
(* Class definition *)
(* ------------------------------------------------------------------------- *)
<<AST class definition>>
(* ------------------------------------------------------------------------- *)
(* Other declarations *)
(* ------------------------------------------------------------------------- *)
<<AST other declaration>>
(* ------------------------------------------------------------------------- *)
(* Stmt bis *)
(* ------------------------------------------------------------------------- *)
<<AST statement bis>>
(* ------------------------------------------------------------------------- *)
(* phpext: *)
(* ------------------------------------------------------------------------- *)
<<AST phpext>>
(* ------------------------------------------------------------------------- *)
(* The toplevels elements *)
(* ------------------------------------------------------------------------- *)
<<AST toplevel>>
(* ------------------------------------------------------------------------- *)
(* Entity and any *)
(* ------------------------------------------------------------------------- *)
<<AST entity>>
<<AST any>>
(* with tarzan *)
(*****************************************************************************)
(* AST helpers *)
(*****************************************************************************)
<<AST helpers interface>>
@
\subsection{AST example}
Before explaining in details each of those AST types,
we will first see how look the full AST of a simple PHP program:
\l just to get a feeling about the high level structure ?
<<foo1.php>>=
<?php
function foo($a) {
echo $a;
}
foo("hello world");
?>
@
One way to see the AST of this program is to use the OCaml interpreter
and its builtin support for pretty printing OCaml values. First we
need to build a custom interpreter [[pfff.top]] (using [[ocamlmktop]])
containing all the necessary modules:
\begin{verbatim}
$ make pfff.top
\end{verbatim}
Once [[pfff.top]] is built, you can run it. You should get an OCaml prompt
(the \#, not to confuse with the shell prompt \$):
\begin{verbatim}
$ ./pfff.top -I commons -I parsing_php
Objective Caml version 3.11.1
#
\end{verbatim}
\label{sec:use-pfff-dot-top}
You can now call any \pfff functions (or any OCaml functions) directly.
\l useful to debug. more on that later
For instance to parse [[demos/foo1.php]] type:
\begin{verbatim}
# Parse_php.parse "demos/foo1.php";;
\end{verbatim}
Here is what the interpreter should display (some
repetitive parts have been ellided):
\begin{verbatim}
- : Parse_php.program2 * Parse_php.parsing_stat =
([(Ast_php.FuncDef
{Ast_php.f_tok =
{Ast_php.pinfo =
Ast_php.OriginTok
{Common.str = "function"; Common.charpos = 6; Common.line = 2;
Common.column = 0; Common.file = "demos/foo1.php"};
Ast_php.comments = ()};
Ast_php.f_ref = None;
Ast_php.f_name =
Ast_php.Name
("foo",
{Ast_php.pinfo =
Ast_php.OriginTok
{Common.str = "foo"; Common.charpos = 15; Common.line = 2;
Common.column = 9; Common.file = "demos/foo1.php"};
Ast_php.comments = ()});
Ast_php.f_params =
({Ast_php.pinfo =
Ast_php.OriginTok
{Common.str = "("; Common.charpos = 18; Common.line = 2;
Common.column = 12; Common.file = "demos/foo1.php"};
...
("<?php\nfunction foo($a) {\n echo $a;\n}",
[Parser_php.T_OPEN_TAG
{Ast_php.pinfo =
Ast_php.OriginTok
{Common.str = "<?php\n"; Common.charpos = 0; Common.line = 1;
Common.column = 0; Common.file = "demos/foo1.php"};
Ast_php.comments = ()};
Parser_php.T_FUNCTION
{Ast_php.pinfo =
Ast_php.OriginTok
{Common.str = "function"; Common.charpos = 6; Common.line = 2;
Common.column = 0; Common.file = "demos/foo1.php"};
Ast_php.comments = ()};
Parser_php.T_WHITESPACE
{Ast_php.pinfo =
Ast_php.OriginTok
{Common.str = " "; Common.charpos = 14; Common.line = 2;
Common.column = 8; Common.file = "demos/foo1.php"};
Ast_php.comments = ()};
...]));
...],
...)
\end{verbatim}
We can see on the first line the infered type
([[Parse_php.program2 * Parse_php.parsing_stat]])
mentionned in the previous chapter.
Then there is one of the raw AST element ([[FuncDef ...]]),
its string representation, and the tokens it was made of
([[T_OPEN_TAG ...]]).
As mentionned earlier, the AST contains the full information
about the program, including the position of its different elements.
This leads to all those [[OriginTok {... Common.line = ...}]] elements.
To see a more compact representation of the AST, one can
use the [[program_of_program2]] function mentionned in the previous
chapter, as well as the
[[abstract_position_info_program]] function
that replaces all the [[OriginTok]] elements by another constructor ([[Ab]]
for abstract). See section~\ref{sec:abstract-line} for
more information.
\l note the T_WHITESPACE
Here are the magic incantations:
\begin{verbatim}
# open Ast_php;;
# let (prog2, _stat) = Parse_php.parse "demos/foo1.php";;
val prog2 : Parse_php.program2 =
...
# let prog = Parse_php.program_of_program2 prog2;;
...
# Lib_parsing_php.abstract_position_info_program prog;;
\end{verbatim}
The OCaml interpreter should now display the following:
\begin{verbatim}
- : Ast_php.program =
[FuncDef
{f_tok = {pinfo = Ab; comments = ()}; f_ref = None;
f_name = Name ("foo", {pinfo = Ab; comments = ()});
f_params =
({pinfo = Ab; comments = ()},
[{p_type = None; p_ref = None;
p_name = DName ("a", {pinfo = Ab; comments = ()}); p_default = None}],
{pinfo = Ab; comments = ()});
f_body =
({pinfo = Ab; comments = ()},
[Stmt
(Echo ({pinfo = Ab; comments = ()},
[(ExprVar
(Var (DName ("a", {pinfo = Ab; comments = ()}),
{contents = Scope_php.NoScope}),
{tvar = [Type_php.Unknown]}),
{t = [Type_php.Unknown]})],
{pinfo = Ab; comments = ()}))],
{pinfo = Ab; comments = ()});
f_type = Type_php.Function ([Type_php.Unknown], [])};
StmtList
[ExprStmt
((ExprVar
(FunCallSimple (None, Name ("foo", {pinfo = Ab; comments = ()}),
({pinfo = Ab; comments = ()},
[Arg
(Scalar
(Constant (String ("hello world", {pinfo = Ab; comments = ()}))),
{t = [Type_php.Unknown]})],
{pinfo = Ab; comments = ()})),
{tvar = [Type_php.Unknown]}),
{t = [Type_php.Unknown]}),
{pinfo = Ab; comments = ()})];
FinalDef {pinfo = Ab; comments = ()}]
\end{verbatim}
Another way to display the AST of a PHP program is to call
the custom PHP AST pretty printer defined in [[sexp_ast_php.ml]]
(see Chapter~\ref{chapter:unparsing})
which can be accessed via the [[-dump_ast]] command line flag as in:
\begin{verbatim}
$ ./pfff -dump_ast demos/foo1.php
\end{verbatim}
This is arguably easier than using [[pfff.top]] which requires a little
bit of gymnastic. Here is the output of the previous command:
\begin{verbatim}
((FuncDef
((f_tok "") (f_ref ()) (f_name (Name ('foo' "")))
(f_params
("" (((p_type ()) (p_ref ()) (p_name (DName ('a' ""))) (p_default ())))
""))
(f_body
(""
((Stmt
(Echo ""
(((ExprVar ((Var (DName ('a' "")) "") ((tvar (Unknown)))))
((t (Unknown)))))
"")))
""))
(f_type (Function (Unknown) ()))))
(StmtList
((ExprStmt
((ExprVar
((FunCallSimple () (Name ('foo' ""))
(""
((Arg
((Scalar (Constant (String ("'hello world'" ""))))
((t (Unknown))))))
""))
((tvar (Unknown)))))
((t (Unknown))))
"")))
(FinalDef ""))
\end{verbatim}
\label{sec:use-dump-on-foo1}
The ability to easily see the internal representation of
PHP programs in \pfff is very useful for beginners who may not
be familiar with the more than 100 constructors defined
in [[ast_php.mli]] (and detailed in the next sections).
Indeed, a common way to write a \pfff analysis is to write
a few test PHP programs, see the corresponding constructors
with the help of the [[pfff -dump_ast]] command, copy paste parts of the output
in your code, and finally write the algorithm to handle
those different constructors.
\subsection{Conventions}
In the AST definitions below I sometimes use the tag [[(* semantic: *)]] in
comments which means that such information is not computed at parsing
time but may be added later in some post processing stage (by code in
[[pfff/analyze_php/]]).
What follows is the full definition of the abstract syntax tree of PHP 5.2.
\t PHP 5.3
\t plus PHP extension such as XHP ?
Right now we keep all the information in this AST, such as the tokens,
the parenthesis, keywords, etc, with the [[tok]] (a.k.a [[info]]) type used
in many constructions (see Section~\ref{sec:ast-info}).
This makes it easier to pretty print back
this AST and to do source-to-source transformations. So it's actually
more a Concrete Syntax Tree (CST) than an Abstract Syntax Tree (AST)
\footnote{Maybe one day we will have a [[real_ast_php.ml]]
([[mini_php/ast_mini_php.ml]] can partly play this role to experiment
with new algorithms for now)}
\footnote{This is not either completely
a CST. It does not follow exactly the grammar; there is not one constructor
per grammar rule. Some grammar rules exist because of
the limitations of the LALR algorithm; the CST does not have to
suffer from this. Moreover a few things were simplified, for instance
compare the [[variable]] type and the [[variable]] grammar rule.
}.
I sometimes annotate this [[tok]]
type with a comment indicating to what concrete symbol the token
corresponds to in the parsed file. For instance for this constructor
[[| AssignRef of variable * tok (* = *) * tok (* & *) * variable]],
the first [[tok]] will contain information regarding the '=' symbol
in the parsed file, and the second [[tok]] information regarding '\&'.
If at some point you want to give an error message regarding a certain
token, then use the helper functions on [[tok]] (or [[info]]) described
in Section~\ref{sec:ast-helper-tok}.
\section{Expressions}
\label{sec:ast-expr}
\label{sec:ast-expr-var}
<<AST expression>>=
(* I used to have a 'type expr = exprbis * exp_type_info' but it complicates
* many patterns when working on expressions, and it turns out I never
* implemented the type annotater. It's easier to do such annotater on
* a real AST like the PIL. So just have this file be a simple concrete
* syntax tree and no more.
*)
type expr =
<<type exp_info>>
| Lv of lvalue
(* start of expr_without_variable in original PHP lexer/parser terminology *)
| Sc of scalar
<<exprbis other constructors>>
(* xhp: *)
| XhpHtml of xhp_html
(* php-facebook-ext:
*
* todo: this should be at the statement level as there are only a few
* forms of yield that hphp support (e.g. yield <expr>; and
* <lval> = yield <expr>). One could then have a YieldReturn and YieldAssign
* but this may change and none of the analysis in pfff need to
* understand yield so for now just make it simple and add yield
* at the expression level.
*)
| Yield of tok * expr
| YieldBreak of tok * tok
<<type exprbis hook>>
<<type scalar and constant and encaps>>
<<AST expression operators>>
<<AST expression rest>>
and xhp_html =
| Xhp of xhp_tag wrap * xhp_attribute list * tok (* > *) *
xhp_body list * xhp_tag option wrap
| XhpSingleton of xhp_tag wrap * xhp_attribute list * tok (* /> *)
and xhp_attribute = xhp_attr_name * tok (* = *) * xhp_attr_value
and xhp_attr_name = string wrap (* e.g. task-bar *)
and xhp_attr_value =
| XhpAttrString of tok (* '"' *) * encaps list * tok (* '"' *)
| XhpAttrExpr of expr brace
(* sgrep: *)
| SgrepXhpAttrValueMvar of string wrap
and xhp_body =
| XhpText of string wrap
| XhpExpr of expr brace
| XhpNested of xhp_html
@
The [[ExprVar]] constructor is explained later. It corresponds
essentially to lvalue expressions (variables, but also function calls).
Scalars are described in the next section, followed by the description of the
remaining expression constructions (e.g. additions).
\footnote{
The [[expr_without_variable]] grammar element is merged
with [[expr]] in the AST
as most of the time in the grammar they use both a case for
[[expr_without_variable]] and a case for [[variable]]. The only difference
is in [[Foreach]] so it's not worthwhile to complicate things just for
[[Foreach]].
}
\subsection{Scalars, constants, encapsulated strings}
<<type scalar and constant and encaps>>=
and scalar =
| C of constant
| ClassConstant of qualifier * name
| Guil of tok (* '"' or b'"' *) * encaps list * tok (* '"' *)
| HereDoc of
tok (* < < < EOF, or b < < < EOF *) *
encaps list *
tok (* EOF; *)
(* | StringVarName??? *)
<<type constant>>
<<type encaps>>
@
\subsubsection{Constants}
<<type constant>>=
and constant =
<<constant constructors>>
<<type constant hook>>
<<constant rest>>
@
Here are the basic constants, numbers:
<<constant constructors>>=
| Int of string wrap
| Double of string wrap
@
I put [[string]] for [[Int]] (and [[Double]]) because [[int]] would not
be enough as OCaml ints are only 31 bits. So it is simpler to use strings.
%C: Same reason to have string instead of int list for the String case.
Note that [[-2]] is not a constant; it is the unary operator [[-]]
([[Unary (UnMinus ...)]]) applied to the constant 2.
So the string in [[Int]] must represent a positive integer only.
\t wrap ??
Strings in PHP comes in two forms: constant strings
and dynamic strings (aka interpolated or encapsulated strings).
In this section we are concerned only with the former.
\l The later is described later.
%in Section~\ref{sec:encaps-strings}.
<<constant constructors>>=
(* see also Guil for interpolated strings
* The string does not contain the enclosing '"' or "'".
* It does not contain either the possible 'b' prefix
*)
| String of string wrap
@
The [[string]] part does not include the enclosing guillemet
[['"']] or quote [[']].
The info itself (in [[wrap]]) will usually contain
it, but not
always! Indeed if the constant we build is part of a bigger encapsulated
strings as in [[echo "$x[foo]"]] then the [[foo]] will be parsed
as a [[String]], even if in the text it appears as a name.
\t So this token is kind of a FakeTok sometimes.
\footnote{If at some point you want to do some program transformation,
you may have to normalize this [[string wrap]] before moving it
in another context !!!}
\t it can even be an integer ... cf T_NUM_STRING in the lexer and grammar
Some identifiers have special meaning in PHP such as [[true]],
[[false]], [[null]]. They are parsed as [[CName]]:
<<constant constructors>>=
| CName of name (* true, false, null, or defined constant *)
@
\t use fore more ?
PHP also supports [[__FILE__]] and other directives inspired by
the C preprocessor [[cpp]]:
<<constant constructors>>=
| PreProcess of cpp_directive wrap
@
<<constant rest>>=
<<type cpp_directive>>
@
<<type cpp_directive>>=
(* http://php.net/manual/en/language.constants.predefined.php *)
and cpp_directive =
| Line | File | Dir
| ClassC | TraitC
| MethodC | FunctionC
@
\subsubsection{Encapsulated strings}
\label{sec:encaps-strings}
Strings interpolation in PHP is complicated and documented here:
\url{http://php.net/manual/en/language.types.string.php}
in the "variable parsing" section.
<<type encaps>>=
and encaps =
<<encaps constructors>>
@
<<encaps constructors>>=
| EncapsString of string wrap
@
\begin{verbatim}
(* for "xx $beer". I put EncapsVar variable, but if you look
* at the grammar it's actually a subset of variable, but I didn't
* want to duplicate subparts of variable here.
*)
\end{verbatim}
<<encaps constructors>>=
| EncapsVar of lvalue
@
<<encaps constructors>>=
(* for "xx {$beer}s" *)
| EncapsCurly of tok * lvalue * tok
@
<<encaps constructors>>=
(* for "xx ${beer}s" *)
| EncapsDollarCurly of tok (* '${' *) * lvalue * tok
@
<<encaps constructors>>=
| EncapsExpr of tok * expr * tok
@
\subsection{Basic expressions}
PHP supports the usual arithmetic ([[+]], [[-]], etc)
and logic expressions inherited from C:
<<exprbis other constructors>>=
| Binary of expr * binaryOp wrap * expr
| Unary of unaryOp wrap * expr
@
<<AST expression operators>>=
and fixOp = Dec | Inc
and binaryOp = Arith of arithOp | Logical of logicalOp
<<php concat operator>>
and arithOp =
| Plus | Minus | Mul | Div | Mod
| DecLeft | DecRight
| And | Or | Xor
and logicalOp =
| Inf | Sup | InfEq | SupEq
| Eq | NotEq
<<php identity operators>>
| AndLog | OrLog | XorLog
| AndBool | OrBool (* diff with AndLog ? short-circuit operators ? *)
and assignOp = AssignOpArith of arithOp
<<php assign concat operator>>
and unaryOp =
| UnPlus | UnMinus
| UnBang | UnTilde
@
\l lexer crossref ?
It also defines new operators for string concatenation
<<php concat operator>>=
| BinaryConcat (* . *)
@
<<php assign concat operator>>=
| AssignConcat (* .= *)
@
and object comparisons:
<<php identity operators>>=
| Identical (* === *) | NotIdentical (* !== *)
@
It also inherits the [[+=]], [[++]] and other
side effect expression (that really should not be
expression):
<<exprbis other constructors>>=
(* should be a statement ... *)
| Assign of lvalue * tok (* = *) * expr
| AssignOp of lvalue * assignOp wrap * expr
| Postfix of rw_variable * fixOp wrap
| Infix of fixOp wrap * rw_variable
@
The ugly conditional ternary operator:
<<exprbis other constructors>>=
(* PHP 5.3 allow 'expr ?: expr' hence the 'option' type below
* from www.php.net/manual/en/language.operators.comparison.php#language.operators.comparison.ternary:
* "Since PHP 5.3, it is possible to leave out the middle part of the
* ternary operator. Expression
* expr1 ?: expr3 returns expr1 if expr1 evaluates to TRUE, and expr3
* otherwise."
*)
| CondExpr of expr * tok (* ? *) * expr option * tok (* : *) * expr
@
\subsection{Value constructions}
<<exprbis other constructors>>=
| AssignList of tok (* list *) * list_assign comma_list paren *
tok (* = *) * expr
| ArrayLong of tok (* array *) * array_pair comma_list paren
(* php 5.4: https://wiki.php.net/rfc/shortsyntaxforarrays *)
| ArrayShort of array_pair comma_list bracket
@
<<AST expression rest>>=
and list_assign =
| ListVar of lvalue
| ListList of tok * list_assign comma_list paren
| ListEmpty
@
<<AST expression rest>>=
and array_pair =
| ArrayExpr of expr
| ArrayRef of tok (* & *) * lvalue
| ArrayArrowExpr of expr * tok (* => *) * expr
| ArrayArrowRef of expr * tok (* => *) * tok (* & *) * lvalue
@
\subsection{Object constructions}
<<exprbis other constructors>>=
| New of tok * class_name_reference * argument comma_list paren option
| Clone of tok * expr
@
<<exprbis other constructors>>=
| AssignRef of lvalue * tok (* = *) * tok (* & *) * lvalue
| AssignNew of lvalue * tok (* = *) * tok (* & *) * tok (* new *) *
class_name_reference *
argument comma_list paren option
@
\l related to Assign
<<AST expression rest>>=
and class_name_reference =
| ClassNameRefStatic of class_name_or_kwd
| ClassNameRefDynamic of lvalue * obj_prop_access list
and obj_prop_access = tok (* -> *) * obj_property
@
\l (* originally base_ *) variable for ClassNameRefDynamic
\subsection{Cast}
<<exprbis other constructors>>=
| Cast of castOp wrap * expr
| CastUnset of tok * expr (* ??? *)
@
<<AST expression operators>>=
and castOp = ptype
@
<<exprbis other constructors>>=
| InstanceOf of expr * tok * class_name_reference
@
\subsection{Eval}
<<exprbis other constructors>>=
(* !The evil eval! *)
| Eval of tok * expr paren
@
\subsection{Anonymous functions (PHP 5.3)}
<<exprbis other constructors>>=
(* Woohoo, viva PHP 5.3 *)
| Lambda of lambda_def
@
<<AST lambda definition>>=
and lambda_def = {
l_tok: tok; (* function *)
l_ref: is_ref;
(* no l_name, anonymous *)
l_params: parameter comma_list_dots paren;
l_use: lexical_vars option;
l_body: stmt_and_def list brace;
}
and lexical_vars = tok (* use *) * lexical_var comma_list paren
and lexical_var =
| LexicalVar of is_ref * dname
@
\subsection{Misc}
<<exprbis other constructors>>=
(* should be a statement ... *)
| Exit of tok * (expr option paren) option
| At of tok (* @ *) * expr
| Print of tok * expr
@
<<exprbis other constructors>>=
| BackQuote of tok * encaps list * tok
@
<<exprbis other constructors>>=
(* should be at toplevel *)
| Include of tok * expr
| IncludeOnce of tok * expr
| Require of tok * expr
| RequireOnce of tok * expr
@
<<exprbis other constructors>>=
| Empty of tok * lvalue paren
| Isset of tok * lvalue comma_list paren
@
\section{Lvalue expressions}
% called variable in PHP grammar, but really lvalue
The [[lvalue]] type below allows a superset of what the PHP grammar actually
permits. See the [[variable2]] type in [[parser_php.mly]] for a more precise,
but far less convenient type to use.
\footnote{Note that with XHP, we are less a superset
because XHP also relaxed some constraints.}
<<AST lvalue>>=
and lvalue =
<<type lvalue_info>>
<<lvaluebis constructors>>
<<type lvalue aux>>
(* semantic: those grammar rule names were used in the original PHP
* lexer/parser but not enforced. It's just comments. *)
and rw_variable = lvalue
and r_variable = lvalue
and w_variable = lvalue
@
\subsection{Basic variables}
Here is the constructor for simple variables, as in [[$foo]]:
<<lvaluebis constructors>>=
| Var of dname *
<<scope_php annotation>>
@
\t hence lvalue type, dname for dollar name
The 'd' in [[dname]] stands for dollar (dollar name).
<<lvaluebis constructors>>=
| This of tok
(* xhp: normally we can not have a FunCall in the lvalue of VArrayAccess,
* but with xhp we can.
*
* todo? a VArrayAccessSimple with Constant string in expr ?
*)
| VArrayAccess of lvalue * expr option bracket
| VArrayAccessXhp of expr * expr option bracket
@
\subsection{Indirect variables}
<<lvaluebis constructors>>=
| VBrace of tok * expr brace
| VBraceAccess of lvalue * expr brace
@
<<lvaluebis constructors>>=
(* on the left of var *)
| Indirect of lvalue * indirect
@
<<type lvalue aux>>=
and indirect = Dollar of tok
@
<<lvaluebis constructors>>=
(* Note that even if A::$v['fld'] was parsed in the grammar
* as a Qualifier(A, ArrayAccess($v, 'fld') we
* generate a ArrayAccess(Qualifier(A, $v), 'fld').
* todo? could merge 3 cases if qualifier allow some dname.
*)
| VQualifier of qualifier * lvalue
(* note that can be a late static class var since php 5.3 *)
| ClassVar of qualifier * dname
(* used to be lvalue * dname but can have code like $class::$$prop *)
| DynamicClassVar of lvalue * tok (* :: *) * lvalue
@
\subsection{Function calls}
\label{sec:funcall}
Function calls are considered as part of the [[lvalue]]
category in the original PHP grammar.
This is probably because functions can return
reference to variables (whereas additions can't).
<<lvaluebis constructors>>=
| FunCallSimple of name * argument comma_list paren
(* DynamicFunCall *)
| FunCallVar of qualifier option * lvalue * argument comma_list paren
@
<<type lvalue aux>>=
and argument =
| Arg of expr
| ArgRef of tok * w_variable
@
%\paragraph{Redundant but convenient constructors}
A few constructs have [[Simple]] as a suffix. They just correspond to
inlined version of other constructs that were put in their own
constructor because they occur very often or are conceptually important
and deserve their own constructor (for instance [[FunCallSimple]]
%in Section~\ref{sec:funcall}
which otherwise would force the programmer to match over more nested
constructors to check if a [[Funcall]] has a static name). On one hand
it makes it easier to match specific construct, on the other hand
when you write an algorithm it forces you to do a little duplication.
But usually I first write the algorithm to handle the easy cases anyway
and I end up not coding the complex one so ...
\subsection{Method and object accesses}
\begin{verbatim}
(* TODO go further by having a dname for the variable ? or make a
* type simple_dvar = dname * Scope_php.phpscope ref and
* put here a simple_dvar ?
*)
\end{verbatim}
<<lvaluebis constructors>>=
(* note that can be a late static call since php 5.3 *)
| StaticMethodCallSimple of qualifier * name * argument comma_list paren
| MethodCallSimple of lvalue * tok * name * argument comma_list paren
(* PHP 5.3 *)
| StaticMethodCallVar of lvalue * tok (* :: *) * name *
argument comma_list paren
| StaticObjCallVar of lvalue * tok (* :: *) * lvalue *
argument comma_list paren
@
<<lvaluebis constructors>>=
| ObjAccessSimple of lvalue * tok (* -> *) * name
| ObjAccess of lvalue * obj_access
@
<<type lvalue aux>>=
and obj_access =
tok (* -> *) * obj_property * argument comma_list paren option
and obj_property =
| ObjProp of obj_dim
| ObjPropVar of lvalue (* was originally var_without_obj *)
(* I would like to remove OName from here, as I inline most of them
* in the MethodCallSimple and ObjAccessSimple above, but they
* can also be mentionned in OArrayAccess in the obj_dim, so
* I keep it
*)
and obj_dim =
| OName of name
| OBrace of expr brace
| OArrayAccess of obj_dim * expr option bracket
| OBraceAccess of obj_dim * expr brace
@
\section{Statements}
\label{sec:ast-stmt}
<<AST statement>>=
(* By introducing Lambda, expr and stmt are now mutually recursive *)
and stmt =
<<stmt constructors>>
(* static-php-ext: *)
| TypedDeclaration of hint_type * lvalue * (tok * expr) option * tok
(* PHP 5.3, see http://us.php.net/const *)
| DeclConstant of tok * name * tok (* = *) * static_scalar * tok (* ; *)
<<AST statement rest>>
@
\subsection{Basic statements}
\label{sec:ast-expr-stmt}
<<stmt constructors>>=
| ExprStmt of expr * tok (* ; *)
| EmptyStmt of tok (* ; *)
@
<<stmt constructors>>=
| Block of stmt_and_def list brace
@
<<stmt constructors>>=
| If of tok * expr paren * stmt *
(* elseif *) if_elseif list *
(* else *) if_else option
<<ifcolon>>
| While of tok * expr paren * colon_stmt
| Do of tok * stmt * tok * expr paren * tok
| For of tok * tok *
for_expr * tok *
for_expr * tok *
for_expr *
tok *
colon_stmt
| Switch of tok * expr paren * switch_case_list
@
<<AST statement rest>>=
and switch_case_list =
| CaseList of
tok (* { *) * tok option (* ; *) * case list * tok (* } *)
| CaseColonList of
tok (* : *) * tok option (* ; *) * case list *
tok (* endswitch *) * tok (* ; *)
and case =
| Case of tok * expr * tok * stmt_and_def list
| Default of tok * tok * stmt_and_def list
and if_elseif = tok * expr paren * stmt
and if_else = (tok * stmt)
@
<<stmt constructors>>=
(* if it's a expr_without_variable, the second arg must be a Right variable,
* otherwise if it's a variable then it must be a foreach_variable
*)
| Foreach of tok * tok * expr * tok * foreach_var_either *
foreach_arrow option * tok *
colon_stmt
(* example: foreach(expr as $lvalue) { colon_stmt }
* foreach(expr as $foreach_varialbe => $lvalue) { colon_stmt}
*)
@
<<AST statement rest>>=
and for_expr = expr comma_list (* can be empty *)
and foreach_arrow = tok * foreach_variable
and foreach_variable = is_ref * lvalue
and foreach_var_either = (foreach_variable, lvalue) Common.either
@
<<stmt constructors>>=
| Break of tok * expr option * tok
| Continue of tok * expr option * tok
| Return of tok * expr option * tok
@
<<stmt constructors>>=
| Throw of tok * expr * tok
| Try of tok * stmt_and_def list brace * catch * catch list
@
<<AST statement rest>>=
and catch =
tok * (fully_qualified_class_name * dname) paren * stmt_and_def list brace