a bugfix on variables
[phpeclipse.git] / net.sourceforge.phpeclipse / src / test / PHPParser.jj
1
2 options {
3   LOOKAHEAD = 1;
4   CHOICE_AMBIGUITY_CHECK = 2;
5   OTHER_AMBIGUITY_CHECK = 1;
6   STATIC = true;
7   DEBUG_PARSER = false;
8   DEBUG_LOOKAHEAD = false;
9   DEBUG_TOKEN_MANAGER = false;
10   OPTIMIZE_TOKEN_MANAGER = false;
11   ERROR_REPORTING = true;
12   JAVA_UNICODE_ESCAPE = false;
13   UNICODE_INPUT = false;
14   IGNORE_CASE = true;
15   USER_TOKEN_MANAGER = false;
16   USER_CHAR_STREAM = false;
17   BUILD_PARSER = true;
18   BUILD_TOKEN_MANAGER = true;
19   SANITY_CHECK = true;
20   FORCE_LA_CHECK = false;
21   COMMON_TOKEN_ACTION = true;
22 }
23
24 PARSER_BEGIN(PHPParser)
25 package test;
26
27 import org.eclipse.core.resources.IFile;
28 import org.eclipse.core.resources.IMarker;
29 import org.eclipse.core.runtime.CoreException;
30 import org.eclipse.ui.texteditor.MarkerUtilities;
31 import org.eclipse.jface.preference.IPreferenceStore;
32
33 import java.util.Hashtable;
34 import java.util.ArrayList;
35 import java.io.StringReader;
36 import java.io.*;
37 import java.text.MessageFormat;
38
39 import net.sourceforge.phpeclipse.actions.PHPStartApacheAction;
40 import net.sourceforge.phpeclipse.PHPeclipsePlugin;
41 import net.sourceforge.phpdt.internal.compiler.ast.*;
42 import net.sourceforge.phpdt.internal.compiler.parser.OutlineableWithChildren;
43 import net.sourceforge.phpdt.internal.compiler.parser.Outlineable;
44 import net.sourceforge.phpdt.internal.compiler.parser.PHPOutlineInfo;
45 import net.sourceforge.phpdt.internal.corext.Assert;
46
47 /**
48  * A new php parser.
49  * This php parser is inspired by the Java 1.2 grammar example
50  * given with JavaCC. You can get JavaCC at http://www.webgain.com
51  * You can test the parser with the PHPParserTestCase2.java
52  * @author Matthieu Casanova
53  */
54 public final class PHPParser extends PHPParserSuperclass {
55
56 //todo : fix the variables names bug
57 //todo : handle tilde operator
58
59
60   /** The current segment. */
61   private static OutlineableWithChildren currentSegment;
62
63   private static final String PARSE_ERROR_STRING = "Parse error"; //$NON-NLS-1$
64   private static final String PARSE_WARNING_STRING = "Warning"; //$NON-NLS-1$
65   static PHPOutlineInfo outlineInfo;
66
67   /** The error level of the current ParseException. */
68   private static int errorLevel = ERROR;
69   /** The message of the current ParseException. If it's null it's because the parse exception wasn't handled */
70   private static String errorMessage;
71
72   private static int errorStart = -1;
73   private static int errorEnd = -1;
74   private static PHPDocument phpDocument;
75
76   private static final String SYNTAX_ERROR_CHAR = "syntax error";
77   /**
78    * The point where html starts.
79    * It will be used by the token manager to create HTMLCode objects
80    */
81   public static int htmlStart;
82
83   //ast stack
84   private final static int AstStackIncrement = 100;
85   /** The stack of node. */
86   private static AstNode[] nodes;
87   /** The cursor in expression stack. */
88   private static int nodePtr;
89
90   public static final boolean PARSER_DEBUG = true;
91
92   public final void setFileToParse(final IFile fileToParse) {
93     PHPParser.fileToParse = fileToParse;
94   }
95
96   public PHPParser() {
97   }
98
99   public PHPParser(final IFile fileToParse) {
100     this(new StringReader(""));
101     PHPParser.fileToParse = fileToParse;
102   }
103
104   public static final void phpParserTester(final String strEval) throws ParseException {
105     final StringReader stream = new StringReader(strEval);
106     if (jj_input_stream == null) {
107       jj_input_stream = new SimpleCharStream(stream, 1, 1);
108     }
109     ReInit(new StringReader(strEval));
110     init();
111     phpDocument = new PHPDocument(null,"_root".toCharArray());
112     currentSegment = phpDocument;
113     outlineInfo = new PHPOutlineInfo(null, currentSegment);
114     PHPParserTokenManager.SwitchTo(PHPParserTokenManager.PHPPARSING);
115     phpTest();
116   }
117
118   public static final void htmlParserTester(final File fileName) throws FileNotFoundException, ParseException {
119     final Reader stream = new FileReader(fileName);
120     if (jj_input_stream == null) {
121       jj_input_stream = new SimpleCharStream(stream, 1, 1);
122     }
123     ReInit(stream);
124     init();
125     phpDocument = new PHPDocument(null,"_root".toCharArray());
126     currentSegment = phpDocument;
127     outlineInfo = new PHPOutlineInfo(null, currentSegment);
128     phpFile();
129   }
130
131   public static final void htmlParserTester(final String strEval) throws ParseException {
132     final StringReader stream = new StringReader(strEval);
133     if (jj_input_stream == null) {
134       jj_input_stream = new SimpleCharStream(stream, 1, 1);
135     }
136     ReInit(stream);
137     init();
138     phpDocument = new PHPDocument(null,"_root".toCharArray());
139     currentSegment = phpDocument;
140     outlineInfo = new PHPOutlineInfo(null, currentSegment);
141     phpFile();
142   }
143
144   /**
145    * Reinitialize the parser.
146    */
147   private static final void init() {
148     nodes = new AstNode[AstStackIncrement];
149     nodePtr = -1;
150     htmlStart = 0;
151   }
152
153   /**
154    * Add an php node on the stack.
155    * @param node the node that will be added to the stack
156    */
157   private static final void pushOnAstNodes(final AstNode node) {
158     try {
159       nodes[++nodePtr] = node;
160     } catch (IndexOutOfBoundsException e) {
161       final int oldStackLength = nodes.length;
162       final AstNode[] oldStack = nodes;
163       nodes = new AstNode[oldStackLength + AstStackIncrement];
164       System.arraycopy(oldStack, 0, nodes, 0, oldStackLength);
165       nodePtr = oldStackLength;
166       nodes[nodePtr] = node;
167     }
168   }
169
170   public final PHPOutlineInfo parseInfo(final Object parent, final String s) {
171     phpDocument = new PHPDocument(parent,"_root".toCharArray());
172     currentSegment = phpDocument;
173     outlineInfo = new PHPOutlineInfo(parent, currentSegment);
174     final StringReader stream = new StringReader(s);
175     if (jj_input_stream == null) {
176       jj_input_stream = new SimpleCharStream(stream, 1, 1);
177     }
178     ReInit(stream);
179     init();
180     try {
181       parse();
182       phpDocument.nodes = new AstNode[nodes.length];
183       System.arraycopy(nodes,0,phpDocument.nodes,0,nodes.length);
184       if (PHPeclipsePlugin.DEBUG) {
185         PHPeclipsePlugin.log(1,phpDocument.toString());
186       }
187     } catch (ParseException e) {
188       processParseException(e);
189     }
190     return outlineInfo;
191   }
192
193   /**
194    * This function will throw the exception if we are in debug mode
195    * and process it if we are in production mode.
196    * this should be fast since the PARSER_DEBUG is static final so the difference will be at compile time
197    * @param e the exception
198    * @throws ParseException the thrown exception
199    */
200   private static void processParseExceptionDebug(final ParseException e) throws ParseException {
201     if (PARSER_DEBUG) {
202       throw e;
203     }
204     processParseException(e);
205   }
206   /**
207    * This method will process the parse exception.
208    * If the error message is null, the parse exception wasn't catched and a trace is written in the log
209    * @param e the ParseException
210    */
211   private static void processParseException(final ParseException e) {
212     if (errorMessage == null) {
213       PHPeclipsePlugin.log(e);
214       errorMessage = "this exception wasn't handled by the parser please tell us how to reproduce it";
215       errorStart = e.currentToken.sourceStart;
216       errorEnd   = e.currentToken.sourceEnd;
217     }
218     setMarker(e);
219     errorMessage = null;
220   //  if (PHPeclipsePlugin.DEBUG) PHPeclipsePlugin.log(e);
221   }
222
223   /**
224    * Create marker for the parse error.
225    * @param e the ParseException
226    */
227   private static void setMarker(final ParseException e) {
228     try {
229       if (errorStart == -1) {
230         setMarker(fileToParse,
231                   errorMessage,
232                   e.currentToken.sourceStart,
233                   e.currentToken.sourceEnd,
234                   errorLevel,
235                   "Line " + e.currentToken.beginLine+", "+e.currentToken.sourceStart+":"+e.currentToken.sourceEnd);
236       } else {
237         setMarker(fileToParse,
238                   errorMessage,
239                   errorStart,
240                   errorEnd,
241                   errorLevel,
242                   "Line " + e.currentToken.beginLine+", "+errorStart+":"+errorEnd);
243         errorStart = -1;
244         errorEnd = -1;
245       }
246     } catch (CoreException e2) {
247       PHPeclipsePlugin.log(e2);
248     }
249   }
250
251   private static void scanLine(final String output,
252                                final IFile file,
253                                final int indx,
254                                final int brIndx) throws CoreException {
255     String current;
256     final StringBuffer lineNumberBuffer = new StringBuffer(10);
257     char ch;
258     current = output.substring(indx, brIndx);
259
260     if (current.indexOf(PARSE_WARNING_STRING) != -1 || current.indexOf(PARSE_ERROR_STRING) != -1) {
261       final int onLine = current.indexOf("on line <b>");
262       if (onLine != -1) {
263         lineNumberBuffer.delete(0, lineNumberBuffer.length());
264         for (int i = onLine; i < current.length(); i++) {
265           ch = current.charAt(i);
266           if ('0' <= ch && '9' >= ch) {
267             lineNumberBuffer.append(ch);
268           }
269         }
270
271         final int lineNumber = Integer.parseInt(lineNumberBuffer.toString());
272
273         final Hashtable attributes = new Hashtable();
274
275         current = current.replaceAll("\n", "");
276         current = current.replaceAll("<b>", "");
277         current = current.replaceAll("</b>", "");
278         MarkerUtilities.setMessage(attributes, current);
279
280         if (current.indexOf(PARSE_ERROR_STRING) != -1)
281           attributes.put(IMarker.SEVERITY, new Integer(IMarker.SEVERITY_ERROR));
282         else if (current.indexOf(PARSE_WARNING_STRING) != -1)
283           attributes.put(IMarker.SEVERITY, new Integer(IMarker.SEVERITY_WARNING));
284         else
285           attributes.put(IMarker.SEVERITY, new Integer(IMarker.SEVERITY_INFO));
286         MarkerUtilities.setLineNumber(attributes, lineNumber);
287         MarkerUtilities.createMarker(file, attributes, IMarker.PROBLEM);
288       }
289     }
290   }
291
292   public final void parse(final String s) {
293     final StringReader stream = new StringReader(s);
294     if (jj_input_stream == null) {
295       jj_input_stream = new SimpleCharStream(stream, 1, 1);
296     }
297     ReInit(stream);
298     init();
299     try {
300       parse();
301     } catch (ParseException e) {
302       processParseException(e);
303     }
304   }
305
306   /**
307    * Call the php parse command ( php -l -f &lt;filename&gt; )
308    * and create markers according to the external parser output
309    */
310   public static void phpExternalParse(final IFile file) {
311     final IPreferenceStore store = PHPeclipsePlugin.getDefault().getPreferenceStore();
312     final String filename = file.getLocation().toString();
313
314     final String[] arguments = { filename };
315     final MessageFormat form = new MessageFormat(store.getString(PHPeclipsePlugin.EXTERNAL_PARSER_PREF));
316     final String command = form.format(arguments);
317
318     final String parserResult = PHPStartApacheAction.getParserOutput(command, "External parser: ");
319
320     try {
321       // parse the buffer to find the errors and warnings
322       createMarkers(parserResult, file);
323     } catch (CoreException e) {
324       PHPeclipsePlugin.log(e);
325     }
326   }
327
328   /**
329    * Put a new html block in the stack.
330    */
331   public static final void createNewHTMLCode() {
332     final int currentPosition = token.sourceStart;
333     if (currentPosition == htmlStart ||
334           currentPosition < htmlStart ||
335           currentPosition > SimpleCharStream.currentBuffer.length()) {
336       return;
337     }
338     final char[] chars = SimpleCharStream.currentBuffer.substring(htmlStart,
339                                                                   currentPosition).toCharArray();
340     pushOnAstNodes(new HTMLCode(chars, htmlStart,currentPosition));
341   }
342
343   /** Create a new task. */
344   public static final void createNewTask(final int todoStart) {
345     final String  todo = SimpleCharStream.currentBuffer.substring(todoStart,
346                                                                   SimpleCharStream.currentBuffer.indexOf("\n",
347                                                                                                          todoStart)-1);
348     if (!PARSER_DEBUG) {
349       try {
350         setMarker(fileToParse,
351                   todo,
352                   SimpleCharStream.getBeginLine(),
353                   TASK,
354                   "Line "+SimpleCharStream.getBeginLine());
355       } catch (CoreException e) {
356         PHPeclipsePlugin.log(e);
357       }
358     }
359   }
360
361   private static final void parse() throws ParseException {
362           phpFile();
363   }
364 }
365
366 PARSER_END(PHPParser)
367
368 TOKEN_MGR_DECLS:
369 {
370   // CommonTokenAction: use the begins/ends fields added to the Jack
371   // CharStream class to set corresponding fields in each Token (which was
372   // also extended with new fields). By default Jack doesn't supply absolute
373   // offsets, just line/column offsets
374   static void CommonTokenAction(Token t) {
375     t.sourceStart = input_stream.beginOffset;
376     t.sourceEnd = input_stream.endOffset;
377   } // CommonTokenAction
378 } // TOKEN_MGR_DECLS
379
380 <DEFAULT> TOKEN :
381 {
382   <PHPSTARTSHORT : "<?">    : PHPPARSING
383 | <PHPSTARTLONG  : "<?php"> : PHPPARSING
384 | <PHPECHOSTART  : "<?=">   : PHPPARSING
385 }
386
387 <PHPPARSING, IN_SINGLE_LINE_COMMENT,IN_VARIABLE> TOKEN :
388 {
389   <PHPEND :"?>"> : DEFAULT
390 }
391
392 /* Skip any character if we are not in php mode */
393 <DEFAULT> SKIP :
394 {
395  < ~[] >
396 }
397
398
399 /* WHITE SPACE */
400 <PHPPARSING> SKIP :
401 {
402   " "
403 | "\t"
404 | "\n"
405 | "\r"
406 | "\f"
407 }
408
409 <IN_VARIABLE> SPECIAL_TOKEN :
410 {
411   " " : PHPPARSING
412 | "\t" : PHPPARSING
413 | "\n" : PHPPARSING
414 | "\r" : PHPPARSING
415 | "\f" : PHPPARSING
416 }
417 /* COMMENTS */
418 <PHPPARSING> SPECIAL_TOKEN :
419 {
420   "//" : IN_SINGLE_LINE_COMMENT
421 | "#"  : IN_SINGLE_LINE_COMMENT
422 | <"/**" ~["/"]> { input_stream.backup(1); } : IN_FORMAL_COMMENT
423 | "/*" : IN_MULTI_LINE_COMMENT
424 }
425
426 <IN_SINGLE_LINE_COMMENT> SPECIAL_TOKEN :
427 {
428   <SINGLE_LINE_COMMENT: "\n" | "\r" | "\r\n" > : PHPPARSING
429 | < ~[] >
430 }
431
432 <IN_SINGLE_LINE_COMMENT,IN_FORMAL_COMMENT,IN_MULTI_LINE_COMMENT> SPECIAL_TOKEN :
433 {
434  "todo"
435 }
436
437 void todo() :
438 {Token todoToken;}
439 {
440   todoToken = "TODO" {createNewTask(todoToken.sourceStart);}
441 }
442 <IN_FORMAL_COMMENT> SPECIAL_TOKEN :
443 {
444   "*/" : PHPPARSING
445 }
446
447 <IN_MULTI_LINE_COMMENT> SPECIAL_TOKEN :
448 {
449   "*/" : PHPPARSING
450 }
451
452 <IN_SINGLE_LINE_COMMENT,IN_FORMAL_COMMENT,IN_MULTI_LINE_COMMENT>
453 MORE :
454 {
455   < ~[] >
456 }
457
458 /* KEYWORDS */
459 <PHPPARSING> TOKEN :
460 {
461   <CLASS    : "class">
462 | <FUNCTION : "function">
463 | <VAR      : "var">
464 | <IF       : "if">
465 | <ELSEIF   : "elseif">
466 | <ELSE     : "else">
467 | <ARRAY    : "array">
468 | <BREAK    : "break">
469 | <LIST     : "list">
470 }
471
472 /* LANGUAGE CONSTRUCT */
473 <PHPPARSING> TOKEN :
474 {
475   <PRINT              : "print">
476 | <ECHO               : "echo">
477 | <INCLUDE            : "include">
478 | <REQUIRE            : "require">
479 | <INCLUDE_ONCE       : "include_once">
480 | <REQUIRE_ONCE       : "require_once">
481 | <GLOBAL             : "global">
482 | <DEFINE             : "define">
483 | <STATIC             : "static">
484 }
485
486 <PHPPARSING,IN_VARIABLE> TOKEN :
487 {
488   <CLASSACCESS        : "->"> : PHPPARSING
489 | <STATICCLASSACCESS  : "::"> : PHPPARSING
490 | <ARRAYASSIGN        : "=>"> : PHPPARSING
491 }
492
493 /* RESERVED WORDS AND LITERALS */
494
495 <PHPPARSING> TOKEN :
496 {
497   <CASE     : "case">
498 | <CONST    : "const">
499 | <CONTINUE : "continue">
500 | <_DEFAULT : "default">
501 | <DO       : "do">
502 | <EXTENDS  : "extends">
503 | <FOR      : "for">
504 | <GOTO     : "goto">
505 | <NEW      : "new">
506 | <NULL     : "null">
507 | <RETURN   : "return">
508 | <SUPER    : "super">
509 | <SWITCH   : "switch">
510 | <THIS     : "this">
511 | <TRUE     : "true">
512 | <FALSE    : "false">
513 | <WHILE    : "while">
514 | <ENDWHILE : "endwhile">
515 | <ENDSWITCH: "endswitch">
516 | <ENDIF    : "endif">
517 | <ENDFOR   : "endfor">
518 | <FOREACH  : "foreach">
519 | <AS       : "as" >
520 }
521
522 /* TYPES */
523 <PHPPARSING> TOKEN :
524 {
525   <STRING  : "string">
526 | <OBJECT  : "object">
527 | <BOOL    : "bool">
528 | <BOOLEAN : "boolean">
529 | <REAL    : "real">
530 | <DOUBLE  : "double">
531 | <FLOAT   : "float">
532 | <INT     : "int">
533 | <INTEGER : "integer">
534 }
535
536 //Misc token
537 <PHPPARSING,IN_VARIABLE> TOKEN :
538 {
539   <AT                 : "@"> : PHPPARSING
540 | <BANG               : "!"> : PHPPARSING
541 | <TILDE              : "~"> : PHPPARSING
542 | <HOOK               : "?"> : PHPPARSING
543 | <COLON              : ":"> : PHPPARSING
544 }
545
546 /* OPERATORS */
547 <PHPPARSING,IN_VARIABLE> TOKEN :
548 {
549   <OR_OR              : "||"> : PHPPARSING
550 | <AND_AND            : "&&"> : PHPPARSING
551 | <PLUS_PLUS          : "++"> : PHPPARSING
552 | <MINUS_MINUS        : "--"> : PHPPARSING
553 | <PLUS               : "+"> : PHPPARSING
554 | <MINUS              : "-"> : PHPPARSING
555 | <STAR               : "*"> : PHPPARSING
556 | <SLASH              : "/"> : PHPPARSING
557 | <BIT_AND            : "&"> : PHPPARSING
558 | <BIT_OR             : "|"> : PHPPARSING
559 | <XOR                : "^"> : PHPPARSING
560 | <REMAINDER          : "%">  : PHPPARSING
561 | <LSHIFT             : "<<"> : PHPPARSING
562 | <RSIGNEDSHIFT       : ">>"> : PHPPARSING
563 | <RUNSIGNEDSHIFT     : ">>>"> : PHPPARSING
564 | <_ORL               : "OR"> : PHPPARSING
565 | <_ANDL              : "AND"> : PHPPARSING
566 }
567
568 /* LITERALS */
569 <PHPPARSING> TOKEN :
570 {
571   <INTEGER_LITERAL:
572         <DECIMAL_LITERAL> (["l","L"])?
573       | <HEX_LITERAL> (["l","L"])?
574       | <OCTAL_LITERAL> (["l","L"])?
575   >
576 |
577   <#DECIMAL_LITERAL: ["1"-"9"] (["0"-"9"])* >
578 |
579   <#HEX_LITERAL: "0" ["x","X"] (["0"-"9","a"-"f","A"-"F"])+ >
580 |
581   <#OCTAL_LITERAL: "0" (["0"-"7"])* >
582 |
583   <FLOATING_POINT_LITERAL:
584         (["0"-"9"])+ "." (["0"-"9"])* (<EXPONENT>)? (["f","F","d","D"])?
585       | "." (["0"-"9"])+ (<EXPONENT>)? (["f","F","d","D"])?
586       | (["0"-"9"])+ <EXPONENT> (["f","F","d","D"])?
587       | (["0"-"9"])+ (<EXPONENT>)? ["f","F","d","D"]
588   >
589 |
590   <#EXPONENT: ["e","E"] (["+","-"])? (["0"-"9"])+ >
591 |
592   <STRING_LITERAL: (<STRING_1> | <STRING_2> | <STRING_3>)>
593 |   <STRING_1: "\"" ( ~["\"","\\"] | "\\" ~[] )* "\"">
594 |   <STRING_2: "'"  ( ~["'","\\"]  | "\\" ~[] )* "'">
595 |   <STRING_3: "`"  ( ~["`","\\"]  | "\\" ~[] )* "`">
596 }
597
598 /* IDENTIFIERS */
599
600
601 <PHPPARSING,IN_VARIABLE> TOKEN : {<DOLLAR : "$"> : IN_VARIABLE}
602
603
604 <PHPPARSING, IN_VARIABLE> TOKEN :
605 {
606   <IDENTIFIER: (<LETTER>|<SPECIAL>) (<LETTER>|<DIGIT>|<SPECIAL>)* >
607 |
608   < #LETTER:
609       ["a"-"z"] | ["A"-"Z"]
610   >
611 |
612   < #DIGIT:
613       ["0"-"9"]
614   >
615 |
616   < #SPECIAL:
617     "_" | ["\u007f"-"\u00ff"]
618   >
619 }
620
621 /* SEPARATORS */
622
623 <PHPPARSING,IN_VARIABLE> TOKEN :
624 {
625   <LPAREN    : "("> : PHPPARSING
626 | <RPAREN    : ")"> : PHPPARSING
627 | <LBRACE    : "{"> : PHPPARSING
628 | <RBRACE    : "}"> : PHPPARSING
629 | <LBRACKET  : "["> : PHPPARSING
630 | <RBRACKET  : "]"> : PHPPARSING
631 | <SEMICOLON : ";"> : PHPPARSING
632 | <COMMA     : ","> : PHPPARSING
633 | <DOT       : "."> : PHPPARSING
634 }
635
636
637 /* COMPARATOR */
638 <PHPPARSING,IN_VARIABLE> TOKEN :
639 {
640   <GT                 : ">"> : PHPPARSING
641 | <LT                 : "<"> : PHPPARSING
642 | <EQUAL_EQUAL        : "=="> : PHPPARSING
643 | <LE                 : "<="> : PHPPARSING
644 | <GE                 : ">="> : PHPPARSING
645 | <NOT_EQUAL          : "!="> : PHPPARSING
646 | <DIF                : "<>"> : PHPPARSING
647 | <BANGDOUBLEEQUAL    : "!=="> : PHPPARSING
648 | <TRIPLEEQUAL        : "==="> : PHPPARSING
649 }
650
651 /* ASSIGNATION */
652 <PHPPARSING,IN_VARIABLE> TOKEN :
653 {
654   <ASSIGN             : "="> : PHPPARSING
655 | <PLUSASSIGN         : "+="> : PHPPARSING
656 | <MINUSASSIGN        : "-="> : PHPPARSING
657 | <STARASSIGN         : "*="> : PHPPARSING
658 | <SLASHASSIGN        : "/="> : PHPPARSING
659 | <ANDASSIGN          : "&="> : PHPPARSING
660 | <ORASSIGN           : "|="> : PHPPARSING
661 | <XORASSIGN          : "^="> : PHPPARSING
662 | <DOTASSIGN          : ".="> : PHPPARSING
663 | <REMASSIGN          : "%="> : PHPPARSING
664 | <TILDEEQUAL         : "~="> : PHPPARSING
665 | <LSHIFTASSIGN       : "<<="> : PHPPARSING
666 | <RSIGNEDSHIFTASSIGN : ">>="> : PHPPARSING
667 }
668
669 void phpTest() :
670 {}
671 {
672   Php()
673   <EOF>
674 }
675
676 void phpFile() :
677 {}
678 {
679   try {
680     (PhpBlock())*
681     {PHPParser.createNewHTMLCode();}
682   } catch (TokenMgrError e) {
683     PHPeclipsePlugin.log(e);
684     errorStart   = SimpleCharStream.beginOffset;
685     errorEnd     = SimpleCharStream.endOffset;
686     errorMessage = e.getMessage();
687     errorLevel   = ERROR;
688     throw generateParseException();
689   }
690 }
691
692 /**
693  * A php block is a <?= expression [;]?>
694  * or <?php somephpcode ?>
695  * or <? somephpcode ?>
696  */
697 void PhpBlock() :
698 {
699   final PHPEchoBlock phpEchoBlock;
700   final Token token,phpEnd;
701 }
702 {
703   phpEchoBlock = phpEchoBlock()
704   {pushOnAstNodes(phpEchoBlock);}
705 |
706   [   <PHPSTARTLONG>
707     | token = <PHPSTARTSHORT>
708     {try {
709       setMarker(fileToParse,
710                 "You should use '<?php' instead of '<?' it will avoid some problems with XML",
711                 token.sourceStart,
712                 token.sourceEnd,
713                 INFO,
714                 "Line " + token.beginLine);
715     } catch (CoreException e) {
716       PHPeclipsePlugin.log(e);
717     }}
718   ]
719   {PHPParser.createNewHTMLCode();}
720   Php()
721   try {
722     phpEnd = <PHPEND>
723    {htmlStart = phpEnd.sourceEnd;}
724   } catch (ParseException e) {
725     errorMessage = "'?>' expected";
726     errorLevel   = ERROR;
727     errorStart = SimpleCharStream.getPosition() - e.currentToken.next.image.length() + 1;
728     errorEnd   = SimpleCharStream.getPosition() + 1;
729     processParseExceptionDebug(e);
730   }
731 }
732
733 PHPEchoBlock phpEchoBlock() :
734 {
735   final Expression expr;
736   final PHPEchoBlock echoBlock;
737   final Token token, token2;
738 }
739 {
740   token = <PHPECHOSTART> {PHPParser.createNewHTMLCode();}
741   expr = Expression() [ <SEMICOLON> ] token2 = <PHPEND>
742   {
743   htmlStart = token2.sourceEnd;
744
745   echoBlock = new PHPEchoBlock(expr,token.sourceStart,token2.sourceEnd);
746   pushOnAstNodes(echoBlock);
747   return echoBlock;}
748 }
749
750 void Php() :
751 {}
752 {
753   (BlockStatement())*
754 }
755
756 ClassDeclaration ClassDeclaration() :
757 {
758   final ClassDeclaration classDeclaration;
759   Token className = null;
760   final Token superclassName, token, extendsToken;
761   String classNameImage = SYNTAX_ERROR_CHAR;
762   String superclassNameImage = null;
763   final int classEnd;
764 }
765 {
766   token = <CLASS>
767   try {
768     className = <IDENTIFIER>
769     {classNameImage = className.image;}
770   } catch (ParseException e) {
771     errorMessage = "unexpected token : '"+ e.currentToken.next.image +"', identifier expected";
772     errorLevel   = ERROR;
773     errorStart   = token.sourceEnd+1;
774     errorEnd     = token.sourceEnd+1;
775     processParseExceptionDebug(e);
776   }
777   [
778     extendsToken = <EXTENDS>
779     try {
780       superclassName = <IDENTIFIER>
781       {superclassNameImage = superclassName.image;}
782     } catch (ParseException e) {
783       errorMessage = "unexpected token : '"+ e.currentToken.next.image +"', identifier expected";
784       errorLevel   = ERROR;
785       errorStart = extendsToken.sourceEnd+1;
786       errorEnd   = extendsToken.sourceEnd+1;
787       processParseExceptionDebug(e);
788       superclassNameImage = SYNTAX_ERROR_CHAR;
789     }
790   ]
791   {
792     int start, end;
793     if (className == null) {
794       start = token.sourceStart;
795       end = token.sourceEnd;
796     } else {
797       start = className.sourceStart;
798       end = className.sourceEnd;
799     }
800     if (superclassNameImage == null) {
801
802       classDeclaration = new ClassDeclaration(currentSegment,
803                                               classNameImage,
804                                               start,
805                                               end);
806     } else {
807       classDeclaration = new ClassDeclaration(currentSegment,
808                                               classNameImage,
809                                               superclassNameImage,
810                                               start,
811                                               end);
812     }
813       currentSegment.add(classDeclaration);
814       currentSegment = classDeclaration;
815   }
816   classEnd = ClassBody(classDeclaration)
817   {currentSegment = (OutlineableWithChildren) currentSegment.getParent();
818    classDeclaration.sourceEnd = classEnd;
819    pushOnAstNodes(classDeclaration);
820    return classDeclaration;}
821 }
822
823 int ClassBody(final ClassDeclaration classDeclaration) :
824 {
825 Token token;
826 }
827 {
828   try {
829     <LBRACE>
830   } catch (ParseException e) {
831     errorMessage = "unexpected token : '"+ e.currentToken.next.image + "'. '{' expected";
832     errorLevel   = ERROR;
833     errorStart = SimpleCharStream.getPosition() - e.currentToken.next.image.length() + 1;
834     errorEnd   = SimpleCharStream.getPosition() + 1;
835     processParseExceptionDebug(e);
836   }
837   ( ClassBodyDeclaration(classDeclaration) )*
838   try {
839     token = <RBRACE>
840     {return token.sourceEnd;}
841   } catch (ParseException e) {
842     errorMessage = "unexpected token : '"+ e.currentToken.next.image +"'. 'var', 'function' or '}' expected";
843     errorLevel   = ERROR;
844     errorStart = SimpleCharStream.getPosition() - e.currentToken.next.image.length() + 1;
845     errorEnd   = SimpleCharStream.getPosition() + 1;
846     processParseExceptionDebug(e);
847     return PHPParser.token.sourceEnd;
848   }
849 }
850
851 /**
852  * A class can contain only methods and fields.
853  */
854 void ClassBodyDeclaration(final ClassDeclaration classDeclaration) :
855 {
856   final MethodDeclaration method;
857   final FieldDeclaration field;
858 }
859 {
860   method = MethodDeclaration() {method.analyzeCode();
861                                 classDeclaration.addMethod(method);}
862 | field = FieldDeclaration()   {classDeclaration.addField(field);}
863 }
864
865 /**
866  * A class field declaration : it's var VariableDeclarator() (, VariableDeclarator())*;.
867  * it is only used by ClassBodyDeclaration()
868  */
869 FieldDeclaration FieldDeclaration() :
870 {
871   VariableDeclaration variableDeclaration;
872   final VariableDeclaration[] list;
873   final ArrayList arrayList = new ArrayList();
874   final Token token;
875   Token token2 = null;
876   int pos;
877 }
878 {
879   token = <VAR> variableDeclaration = VariableDeclaratorNoSuffix()
880   {
881     arrayList.add(variableDeclaration);
882     outlineInfo.addVariable(variableDeclaration.name());
883     pos = variableDeclaration.sourceEnd;
884   }
885   (
886     <COMMA> variableDeclaration = VariableDeclaratorNoSuffix()
887       {
888         arrayList.add(variableDeclaration);
889         outlineInfo.addVariable(variableDeclaration.name());
890         pos = variableDeclaration.sourceEnd;
891       }
892   )*
893   try {
894     token2 = <SEMICOLON>
895   } catch (ParseException e) {
896     errorMessage = "unexpected token : '"+ e.currentToken.next.image +"'. A ';' was expected after variable declaration";
897     errorLevel   = ERROR;
898     errorStart   = pos+1;
899     errorEnd     = pos+1;
900     processParseExceptionDebug(e);
901   }
902
903   {list = new VariableDeclaration[arrayList.size()];
904    arrayList.toArray(list);
905    int end;
906    if (token2 == null) {
907      end = list[list.length-1].sourceEnd;
908    } else {
909      end = token2.sourceEnd;
910    }
911    return new FieldDeclaration(list,
912                                token.sourceStart,
913                                end,
914                                currentSegment);}
915 }
916
917 /**
918  * a strict variable declarator : there cannot be a suffix here.
919  * It will be used by fields and formal parameters
920  */
921 VariableDeclaration VariableDeclaratorNoSuffix() :
922 {
923   final Token token, lbrace,rbrace;
924   Expression expr, initializer = null;
925   Token assignToken;
926   Variable variable;
927 }
928 {
929   <DOLLAR>
930   (
931      token = <IDENTIFIER>
932      {variable = new Variable(token.image,token.sourceStart,token.sourceEnd);}
933    |
934      lbrace = <LBRACE> expr = Expression() rbrace = <RBRACE>
935      {variable = new Variable(expr,lbrace.sourceStart,rbrace.sourceEnd);}
936   )
937   [
938     assignToken = <ASSIGN>
939     try {
940       initializer = VariableInitializer()
941     } catch (ParseException e) {
942       errorMessage = "Literal expression expected in variable initializer";
943       errorLevel   = ERROR;
944       errorStart = assignToken.sourceEnd +1;
945       errorEnd   = assignToken.sourceEnd +1;
946       processParseExceptionDebug(e);
947     }
948   ]
949   {
950   if (initializer == null) {
951     return new VariableDeclaration(currentSegment,
952                                    variable,
953                                    variable.sourceStart,
954                                    variable.sourceEnd);
955   }
956   return new VariableDeclaration(currentSegment,
957                                  variable,
958                                  initializer,
959                                  VariableDeclaration.EQUAL,
960                                  variable.sourceStart);
961   }
962 }
963
964 /**
965  * this will be used by static statement
966  */
967 VariableDeclaration VariableDeclarator() :
968 {
969   final AbstractVariable variable;
970   Expression initializer = null;
971   final Token token;
972 }
973 {
974   variable = VariableDeclaratorId()
975   [
976     token = <ASSIGN>
977     try {
978       initializer = VariableInitializer()
979     } catch (ParseException e) {
980       errorMessage = "Literal expression expected in variable initializer";
981       errorLevel   = ERROR;
982       errorStart = token.sourceEnd+1;
983       errorEnd   = token.sourceEnd+1;
984       processParseExceptionDebug(e);
985     }
986   ]
987   {
988   if (initializer == null) {
989     return new VariableDeclaration(currentSegment,
990                                    variable,
991                                    variable.sourceStart,
992                                    variable.sourceEnd);
993   }
994     return new VariableDeclaration(currentSegment,
995                                    variable,
996                                    initializer,
997                                    VariableDeclaration.EQUAL,
998                                    variable.sourceStart);
999   }
1000 }
1001
1002 /**
1003  * A Variable name.
1004  * @return the variable name (with suffix)
1005  */
1006 AbstractVariable VariableDeclaratorId() :
1007 {
1008   final Variable var;
1009   AbstractVariable expression = null;
1010 }
1011 {
1012   try {
1013     var = Variable()
1014     (
1015       LOOKAHEAD(2)
1016       expression = VariableSuffix(var)
1017     )*
1018     {
1019      if (expression == null) {
1020        return var;
1021      }
1022      return expression;
1023     }
1024   } catch (ParseException e) {
1025     errorMessage = "'$' expected for variable identifier";
1026     errorLevel   = ERROR;
1027     errorStart = SimpleCharStream.getPosition() - e.currentToken.next.image.length() + 1;
1028     errorEnd   = SimpleCharStream.getPosition() + 1;
1029     throw e;
1030   }
1031 }
1032
1033 Variable Variable() :
1034 {
1035   Variable variable = null;
1036   final Token token;
1037 }
1038 {
1039   token = <DOLLAR> variable = Var(token)
1040   {
1041     return new Variable(variable,token.sourceEnd,variable.sourceEnd);
1042   }
1043 }
1044
1045 Variable Var(final Token dollar) :
1046 {
1047   Variable variable = null;
1048   final Token token,token2;
1049   ConstantIdentifier constant;
1050   Expression expression;
1051 }
1052 {
1053   token = <DOLLAR> variable = Var(token)
1054   {return new Variable(variable,dollar.sourceEnd,variable.sourceEnd);}
1055 |
1056   token = <LBRACE> expression = Expression() token2 = <RBRACE>
1057   {
1058    return new Variable(expression,
1059                        dollar.sourceStart,
1060                        token2.sourceEnd);
1061   }
1062 |
1063   token = <IDENTIFIER>
1064   {return new Variable(token.image,dollar.sourceStart,token.sourceEnd);}
1065 }
1066
1067 Expression VariableInitializer() :
1068 {
1069   final Expression expr;
1070   final Token token, token2;
1071 }
1072 {
1073   expr = Literal()
1074   {return expr;}
1075 |
1076   token2 = <MINUS> (token = <INTEGER_LITERAL> | token = <FLOATING_POINT_LITERAL>)
1077   {return new PrefixedUnaryExpression(new NumberLiteral(token),
1078                                       OperatorIds.MINUS,
1079                                       token2.sourceStart);}
1080 |
1081   token2 = <PLUS> (token = <INTEGER_LITERAL> | token = <FLOATING_POINT_LITERAL>)
1082   {return new PrefixedUnaryExpression(new NumberLiteral(token),
1083                                       OperatorIds.PLUS,
1084                                       token2.sourceStart);}
1085 |
1086   expr = ArrayDeclarator()
1087   {return expr;}
1088 |
1089   token = <IDENTIFIER>
1090   {return new ConstantIdentifier(token);}
1091 }
1092
1093 ArrayVariableDeclaration ArrayVariable() :
1094 {
1095 final Expression expr,expr2;
1096 }
1097 {
1098   expr = Expression()
1099   [
1100     <ARRAYASSIGN> expr2 = Expression()
1101     {return new ArrayVariableDeclaration(expr,expr2);}
1102   ]
1103   {return new ArrayVariableDeclaration(expr,SimpleCharStream.getPosition());}
1104 }
1105
1106 ArrayVariableDeclaration[] ArrayInitializer() :
1107 {
1108   ArrayVariableDeclaration expr;
1109   final ArrayList list = new ArrayList();
1110 }
1111 {
1112   <LPAREN>
1113     [
1114       expr = ArrayVariable()
1115       {list.add(expr);}
1116       ( LOOKAHEAD(2) <COMMA> expr = ArrayVariable()
1117       {list.add(expr);}
1118       )*
1119     ]
1120     [
1121       <COMMA> {list.add(null);}
1122     ]
1123   <RPAREN>
1124   {
1125   final ArrayVariableDeclaration[] vars = new ArrayVariableDeclaration[list.size()];
1126   list.toArray(vars);
1127   return vars;}
1128 }
1129
1130 /**
1131  * A Method Declaration.
1132  * <b>function</b> MetodDeclarator() Block()
1133  */
1134 MethodDeclaration MethodDeclaration() :
1135 {
1136   final MethodDeclaration functionDeclaration;
1137   final Block block;
1138   final OutlineableWithChildren seg = currentSegment;
1139   final Token token;
1140 }
1141 {
1142   token = <FUNCTION>
1143   try {
1144     functionDeclaration = MethodDeclarator(token.sourceStart)
1145     {outlineInfo.addVariable(functionDeclaration.name);}
1146   } catch (ParseException e) {
1147     if (errorMessage != null)  throw e;
1148     errorMessage = "unexpected token : '"+ e.currentToken.next.image +"', function identifier expected";
1149     errorLevel   = ERROR;
1150     errorStart = SimpleCharStream.getPosition() - e.currentToken.next.image.length() + 1;
1151     errorEnd   = SimpleCharStream.getPosition() + 1;
1152     throw e;
1153   }
1154   {currentSegment = functionDeclaration;}
1155   block = Block()
1156   {functionDeclaration.statements = block.statements;
1157    currentSegment = seg;
1158    return functionDeclaration;}
1159 }
1160
1161 /**
1162  * A MethodDeclarator.
1163  * [&] IDENTIFIER(parameters ...).
1164  * @return a function description for the outline
1165  */
1166 MethodDeclaration MethodDeclarator(final int start) :
1167 {
1168   Token identifier = null;
1169   Token reference = null;
1170   final Hashtable formalParameters = new Hashtable();
1171   String identifierChar = SYNTAX_ERROR_CHAR;
1172   int end = start;
1173 }
1174 {
1175   [reference = <BIT_AND> {end = reference.sourceEnd;}]
1176   try {
1177     identifier = <IDENTIFIER>
1178     {
1179       identifierChar = identifier.image;
1180       end = identifier.sourceEnd;
1181     }
1182   } catch (ParseException e) {
1183     errorMessage = "unexpected token : '"+ e.currentToken.next.image +"', function identifier expected";
1184     errorLevel   = ERROR;
1185     errorStart = e.currentToken.sourceEnd;
1186     errorEnd   = e.currentToken.next.sourceStart;
1187     processParseExceptionDebug(e);
1188   }
1189   end = FormalParameters(formalParameters)
1190   {
1191   int nameStart, nameEnd;
1192   if (identifier == null) {
1193     if (reference == null) {
1194       nameStart = start + 9;
1195       nameEnd = start + 10;
1196     } else {
1197       nameStart = reference.sourceEnd + 1;
1198       nameEnd = reference.sourceEnd + 2;
1199     }
1200   } else {
1201       nameStart = identifier.sourceStart;
1202       nameEnd = identifier.sourceEnd;
1203   }
1204   return new MethodDeclaration(currentSegment,
1205                                identifierChar,
1206                                formalParameters,
1207                                reference != null,
1208                                nameStart,
1209                                nameEnd,
1210                                start,
1211                                end);
1212   }
1213 }
1214
1215 /**
1216  * FormalParameters follows method identifier.
1217  * (FormalParameter())
1218  */
1219 int FormalParameters(final Hashtable parameters) :
1220 {
1221   VariableDeclaration var;
1222   final Token token;
1223   Token tok = PHPParser.token;
1224   int end = tok.sourceEnd;
1225 }
1226 {
1227   try {
1228   tok = <LPAREN>
1229   {end = tok.sourceEnd;}
1230   } catch (ParseException e) {
1231     errorMessage = "unexpected token : '"+ e.currentToken.next.image +"', '(' expected after function identifier";
1232     errorLevel   = ERROR;
1233     errorStart = e.currentToken.next.sourceStart;
1234     errorEnd   = e.currentToken.next.sourceEnd;
1235     processParseExceptionDebug(e);
1236   }
1237   [
1238     var = FormalParameter()
1239     {parameters.put(var.name(),var);end = var.sourceEnd;}
1240     (
1241       <COMMA> var = FormalParameter()
1242       {parameters.put(var.name(),var);end = var.sourceEnd;}
1243     )*
1244   ]
1245   try {
1246     token = <RPAREN>
1247     {end = token.sourceEnd;}
1248   } catch (ParseException e) {
1249     errorMessage = "')' expected";
1250     errorLevel   = ERROR;
1251     errorStart = e.currentToken.next.sourceStart;
1252     errorEnd   = e.currentToken.next.sourceEnd;
1253     processParseExceptionDebug(e);
1254   }
1255  {return end;}
1256 }
1257
1258 /**
1259  * A formal parameter.
1260  * $varname[=value] (,$varname[=value])
1261  */
1262 VariableDeclaration FormalParameter() :
1263 {
1264   final VariableDeclaration variableDeclaration;
1265   Token token = null;
1266 }
1267 {
1268   [token = <BIT_AND>] variableDeclaration = VariableDeclaratorNoSuffix()
1269   {
1270     if (token != null) {
1271       variableDeclaration.setReference(true);
1272     }
1273     return variableDeclaration;}
1274 }
1275
1276 ConstantIdentifier Type() :
1277 {final Token token;}
1278 {
1279   token = <STRING>    {return new ConstantIdentifier(token);}
1280 | token = <BOOL>      {return new ConstantIdentifier(token);}
1281 | token = <BOOLEAN>   {return new ConstantIdentifier(token);}
1282 | token = <REAL>      {return new ConstantIdentifier(token);}
1283 | token = <DOUBLE>    {return new ConstantIdentifier(token);}
1284 | token = <FLOAT>     {return new ConstantIdentifier(token);}
1285 | token = <INT>       {return new ConstantIdentifier(token);}
1286 | token = <INTEGER>   {return new ConstantIdentifier(token);}
1287 | token = <OBJECT>    {return new ConstantIdentifier(token);}
1288 }
1289
1290 Expression Expression() :
1291 {
1292   final Expression expr;
1293   Expression initializer = null;
1294   int assignOperator = -1;
1295 }
1296 {
1297   LOOKAHEAD(1)
1298   expr = ConditionalExpression()
1299   [
1300     assignOperator = AssignmentOperator()
1301     try {
1302       initializer = Expression()
1303     } catch (ParseException e) {
1304       if (errorMessage != null) {
1305         throw e;
1306       }
1307       errorMessage = "unexpected token : '"+ e.currentToken.next.image +"', expression expected";
1308       errorLevel   = ERROR;
1309       errorEnd   = SimpleCharStream.getPosition();
1310       throw e;
1311     }
1312   ]
1313   {
1314     if (assignOperator != -1) {// todo : change this, very very bad :(
1315         if (expr instanceof AbstractVariable) {
1316           return new VariableDeclaration(currentSegment,
1317                                          (AbstractVariable) expr,
1318                                          initializer,
1319                                          expr.sourceStart,
1320                                          initializer.sourceEnd);
1321         }
1322         String varName = expr.toStringExpression().substring(1);
1323         return new VariableDeclaration(currentSegment,
1324                                        new Variable(varName,
1325                                                     expr.sourceStart,
1326                                                     expr.sourceEnd),
1327                                        expr.sourceStart,
1328                                        initializer.sourceEnd);
1329     }
1330     return expr;
1331   }
1332 | expr = ExpressionWBang()       {return expr;}
1333 }
1334
1335 Expression ExpressionWBang() :
1336 {
1337   final Expression expr;
1338   final Token token;
1339 }
1340 {
1341   token = <BANG> expr = ExpressionWBang()
1342   {return new PrefixedUnaryExpression(expr,OperatorIds.NOT,token.sourceStart);}
1343 | expr = ExpressionNoBang() {return expr;}
1344 }
1345
1346 Expression ExpressionNoBang() :
1347 {
1348   Expression expr;
1349 }
1350 {
1351   expr = ListExpression()    {return expr;}
1352 |
1353   expr = PrintExpression()   {return expr;}
1354 }
1355
1356 /**
1357  * Any assignement operator.
1358  * @return the assignement operator id
1359  */
1360 int AssignmentOperator() :
1361 {}
1362 {
1363   <ASSIGN>             {return VariableDeclaration.EQUAL;}
1364 | <STARASSIGN>         {return VariableDeclaration.STAR_EQUAL;}
1365 | <SLASHASSIGN>        {return VariableDeclaration.SLASH_EQUAL;}
1366 | <REMASSIGN>          {return VariableDeclaration.REM_EQUAL;}
1367 | <PLUSASSIGN>         {return VariableDeclaration.PLUS_EQUAL;}
1368 | <MINUSASSIGN>        {return VariableDeclaration.MINUS_EQUAL;}
1369 | <LSHIFTASSIGN>       {return VariableDeclaration.LSHIFT_EQUAL;}
1370 | <RSIGNEDSHIFTASSIGN> {return VariableDeclaration.RSIGNEDSHIFT_EQUAL;}
1371 | <ANDASSIGN>          {return VariableDeclaration.AND_EQUAL;}
1372 | <XORASSIGN>          {return VariableDeclaration.XOR_EQUAL;}
1373 | <ORASSIGN>           {return VariableDeclaration.OR_EQUAL;}
1374 | <DOTASSIGN>          {return VariableDeclaration.DOT_EQUAL;}
1375 | <TILDEEQUAL>         {return VariableDeclaration.TILDE_EQUAL;}
1376 }
1377
1378 Expression ConditionalExpression() :
1379 {
1380   final Expression expr;
1381   Expression expr2 = null;
1382   Expression expr3 = null;
1383 }
1384 {
1385   expr = ConditionalOrExpression() [ <HOOK> expr2 = Expression() <COLON> expr3 = ConditionalExpression() ]
1386 {
1387   if (expr3 == null) {
1388     return expr;
1389   }
1390   return new ConditionalExpression(expr,expr2,expr3);
1391 }
1392 }
1393
1394 Expression ConditionalOrExpression() :
1395 {
1396   Expression expr,expr2;
1397   int operator;
1398 }
1399 {
1400   expr = ConditionalAndExpression()
1401   (
1402     (
1403         <OR_OR> {operator = OperatorIds.OR_OR;}
1404       | <_ORL>  {operator = OperatorIds.ORL;}
1405     )
1406     expr2 = ConditionalAndExpression()
1407     {
1408       expr = new BinaryExpression(expr,expr2,operator);
1409     }
1410   )*
1411   {return expr;}
1412 }
1413
1414 Expression ConditionalAndExpression() :
1415 {
1416   Expression expr,expr2;
1417   int operator;
1418 }
1419 {
1420   expr = ConcatExpression()
1421   (
1422   (  <AND_AND> {operator = OperatorIds.AND_AND;}
1423    | <_ANDL>   {operator = OperatorIds.ANDL;})
1424    expr2 = ConcatExpression() {expr = new BinaryExpression(expr,expr2,operator);}
1425   )*
1426   {return expr;}
1427 }
1428
1429 Expression ConcatExpression() :
1430 {
1431   Expression expr,expr2;
1432 }
1433 {
1434   expr = InclusiveOrExpression()
1435   (
1436     <DOT> expr2 = InclusiveOrExpression()
1437     {expr = new BinaryExpression(expr,expr2,OperatorIds.DOT);}
1438   )*
1439   {return expr;}
1440 }
1441
1442 Expression InclusiveOrExpression() :
1443 {
1444   Expression expr,expr2;
1445 }
1446 {
1447   expr = ExclusiveOrExpression()
1448   (<BIT_OR> expr2 = ExclusiveOrExpression()
1449    {expr = new BinaryExpression(expr,expr2,OperatorIds.OR);}
1450   )*
1451   {return expr;}
1452 }
1453
1454 Expression ExclusiveOrExpression() :
1455 {
1456   Expression expr,expr2;
1457 }
1458 {
1459   expr = AndExpression()
1460   (
1461     <XOR> expr2 = AndExpression()
1462     {expr = new BinaryExpression(expr,expr2,OperatorIds.XOR);}
1463   )*
1464   {return expr;}
1465 }
1466
1467 Expression AndExpression() :
1468 {
1469   Expression expr,expr2;
1470 }
1471 {
1472   expr = EqualityExpression()
1473   (
1474     LOOKAHEAD(1)
1475     <BIT_AND> expr2 = EqualityExpression()
1476     {expr = new BinaryExpression(expr,expr2,OperatorIds.AND);}
1477   )*
1478   {return expr;}
1479 }
1480
1481 Expression EqualityExpression() :
1482 {
1483   Expression expr,expr2;
1484   int operator;
1485   Token token;
1486 }
1487 {
1488   expr = RelationalExpression()
1489   (
1490   (   token = <EQUAL_EQUAL>      {operator = OperatorIds.EQUAL_EQUAL;}
1491     | token = <DIF>              {operator = OperatorIds.DIF;}
1492     | token = <NOT_EQUAL>        {operator = OperatorIds.DIF;}
1493     | token = <BANGDOUBLEEQUAL>  {operator = OperatorIds.BANG_EQUAL_EQUAL;}
1494     | token = <TRIPLEEQUAL>      {operator = OperatorIds.EQUAL_EQUAL_EQUAL;}
1495   )
1496   try {
1497     expr2 = RelationalExpression()
1498   } catch (ParseException e) {
1499     if (errorMessage != null) {
1500       throw e;
1501     }
1502     errorMessage = "unexpected token : '"+ e.currentToken.next.image +"', expression expected";
1503     errorLevel   = ERROR;
1504     errorStart = token.sourceEnd +1;
1505     errorEnd   = token.sourceEnd +1;
1506     expr2 = new ConstantIdentifier(SYNTAX_ERROR_CHAR,token.sourceEnd +1,token.sourceEnd +1);
1507     processParseExceptionDebug(e);
1508   }
1509   {
1510     expr = new BinaryExpression(expr,expr2,operator);
1511   }
1512   )*
1513   {return expr;}
1514 }
1515
1516 Expression RelationalExpression() :
1517 {
1518   Expression expr,expr2;
1519   int operator;
1520 }
1521 {
1522   expr = ShiftExpression()
1523   (
1524   ( <LT> {operator = OperatorIds.LESS;}
1525   | <GT> {operator = OperatorIds.GREATER;}
1526   | <LE> {operator = OperatorIds.LESS_EQUAL;}
1527   | <GE> {operator = OperatorIds.GREATER_EQUAL;})
1528    expr2 = ShiftExpression()
1529   {expr = new BinaryExpression(expr,expr2,operator);}
1530   )*
1531   {return expr;}
1532 }
1533
1534 Expression ShiftExpression() :
1535 {
1536   Expression expr,expr2;
1537   int operator;
1538 }
1539 {
1540   expr = AdditiveExpression()
1541   (
1542   ( <LSHIFT>         {operator = OperatorIds.LEFT_SHIFT;}
1543   | <RSIGNEDSHIFT>   {operator = OperatorIds.RIGHT_SHIFT;}
1544   | <RUNSIGNEDSHIFT> {operator = OperatorIds.UNSIGNED_RIGHT_SHIFT;})
1545   expr2 = AdditiveExpression()
1546   {expr = new BinaryExpression(expr,expr2,operator);}
1547   )*
1548   {return expr;}
1549 }
1550
1551 Expression AdditiveExpression() :
1552 {
1553   Expression expr,expr2;
1554   int operator;
1555 }
1556 {
1557   expr = MultiplicativeExpression()
1558   (
1559     LOOKAHEAD(1)
1560      ( <PLUS>  {operator = OperatorIds.PLUS;}
1561      | <MINUS> {operator = OperatorIds.MINUS;}
1562   )
1563    expr2 = MultiplicativeExpression()
1564   {expr = new BinaryExpression(expr,expr2,operator);}
1565    )*
1566   {return expr;}
1567 }
1568
1569 Expression MultiplicativeExpression() :
1570 {
1571   Expression expr,expr2;
1572   int operator;
1573 }
1574 {
1575   try {
1576     expr = UnaryExpression()
1577   } catch (ParseException e) {
1578     if (errorMessage != null) throw e;
1579     errorMessage = "unexpected token '"+e.currentToken.next.image+"'";
1580     errorLevel   = ERROR;
1581     errorStart = PHPParser.token.sourceStart;
1582     errorEnd   = PHPParser.token.sourceEnd;
1583     throw e;
1584   }
1585   (
1586    (  <STAR>      {operator = OperatorIds.MULTIPLY;}
1587     | <SLASH>     {operator = OperatorIds.DIVIDE;}
1588     | <REMAINDER> {operator = OperatorIds.REMAINDER;})
1589     expr2 = UnaryExpression()
1590     {expr = new BinaryExpression(expr,expr2,operator);}
1591   )*
1592   {return expr;}
1593 }
1594
1595 /**
1596  * An unary expression starting with @, & or nothing
1597  */
1598 Expression UnaryExpression() :
1599 {
1600   final Expression expr;
1601 }
1602 {
1603  /* <BIT_AND> expr = UnaryExpressionNoPrefix()             //why did I had that ?
1604   {return new PrefixedUnaryExpression(expr,OperatorIds.AND,pos);}
1605 |      */
1606   expr = AtNotTildeUnaryExpression() {return expr;}
1607 }
1608
1609 Expression AtNotTildeUnaryExpression() :
1610 {
1611   final Expression expr;
1612   final Token token;
1613 }
1614 {
1615   token = <AT>
1616   expr = AtNotTildeUnaryExpression()
1617   {return new PrefixedUnaryExpression(expr,OperatorIds.AT,token.sourceStart);}
1618 |
1619   token = <TILDE>
1620   expr = AtNotTildeUnaryExpression()
1621   {return new PrefixedUnaryExpression(expr,OperatorIds.TWIDDLE,token.sourceStart);}
1622 |
1623   token = <BANG>
1624   expr = AtNotUnaryExpression()
1625   {return new PrefixedUnaryExpression(expr,OperatorIds.NOT,token.sourceStart);}
1626 |
1627   expr = UnaryExpressionNoPrefix()
1628   {return expr;}
1629 }
1630
1631 /**
1632  * An expression prefixed (or not) by one or more @ and !.
1633  * @return the expression
1634  */
1635 Expression AtNotUnaryExpression() :
1636 {
1637   final Expression expr;
1638   final Token token;
1639 }
1640 {
1641   token = <AT>
1642   expr = AtNotUnaryExpression()
1643   {return new PrefixedUnaryExpression(expr,OperatorIds.AT,token.sourceStart);}
1644 |
1645   token = <BANG>
1646   expr = AtNotUnaryExpression()
1647   {return new PrefixedUnaryExpression(expr,OperatorIds.NOT,token.sourceStart);}
1648 |
1649   expr = UnaryExpressionNoPrefix()
1650   {return expr;}
1651 }
1652
1653 Expression UnaryExpressionNoPrefix() :
1654 {
1655   final Expression expr;
1656   final Token token;
1657 }
1658 {
1659   token = <PLUS> expr = AtNotTildeUnaryExpression()   {return new PrefixedUnaryExpression(expr,
1660                                                                                      OperatorIds.PLUS,
1661                                                                                      token.sourceStart);}
1662 |
1663   token = <MINUS> expr = AtNotTildeUnaryExpression()  {return new PrefixedUnaryExpression(expr,
1664                                                                                      OperatorIds.MINUS,
1665                                                                                      token.sourceStart);}
1666 |
1667   expr = PreIncDecExpression()
1668   {return expr;}
1669 |
1670   expr = UnaryExpressionNotPlusMinus()
1671   {return expr;}
1672 }
1673
1674
1675 Expression PreIncDecExpression() :
1676 {
1677 final Expression expr;
1678 final int operator;
1679 final Token token;
1680 }
1681 {
1682   (
1683       token = <PLUS_PLUS>   {operator = OperatorIds.PLUS_PLUS;}
1684     |
1685       token = <MINUS_MINUS> {operator = OperatorIds.MINUS_MINUS;}
1686   )
1687   expr = PrimaryExpression()
1688   {return new PrefixedUnaryExpression(expr,operator,token.sourceStart);}
1689 }
1690
1691 Expression UnaryExpressionNotPlusMinus() :
1692 {
1693   final Expression expr;
1694 }
1695 {
1696   LOOKAHEAD( <LPAREN> (Type() | <ARRAY>) <RPAREN> )
1697   expr = CastExpression()         {return expr;}
1698 | expr = PostfixExpression()      {return expr;}
1699 | expr = Literal()                {return expr;}
1700 | <LPAREN> expr = Expression()
1701   try {
1702     <RPAREN>
1703   } catch (ParseException e) {
1704     errorMessage = "')' expected";
1705     errorLevel   = ERROR;
1706     errorStart   = expr.sourceEnd +1;
1707     errorEnd     = expr.sourceEnd +1;
1708     processParseExceptionDebug(e);
1709   }
1710   {return expr;}
1711 }
1712
1713 CastExpression CastExpression() :
1714 {
1715 final ConstantIdentifier type;
1716 final Expression expr;
1717 final Token token,token1;
1718 }
1719 {
1720   token1 = <LPAREN>
1721   (
1722       type = Type()
1723     |
1724       token = <ARRAY> {type = new ConstantIdentifier(token);}
1725   )
1726   <RPAREN> expr = UnaryExpression()
1727   {return new CastExpression(type,expr,token1.sourceStart,expr.sourceEnd);}
1728 }
1729
1730 Expression PostfixExpression() :
1731 {
1732   final Expression expr;
1733   int operator = -1;
1734   Token token = null;
1735 }
1736 {
1737   expr = PrimaryExpression()
1738   [
1739       token = <PLUS_PLUS>   {operator = OperatorIds.PLUS_PLUS;}
1740     |
1741       token = <MINUS_MINUS> {operator = OperatorIds.MINUS_MINUS;}
1742   ]
1743   {
1744     if (operator == -1) {
1745       return expr;
1746     }
1747     return new PostfixedUnaryExpression(expr,operator,token.sourceEnd);
1748   }
1749 }
1750
1751 Expression PrimaryExpression() :
1752 {
1753   Expression expr;
1754   Token token = null;
1755 }
1756 {
1757   [token = <BIT_AND>] expr = refPrimaryExpression(token)
1758   {return expr;}
1759 |
1760   expr = ArrayDeclarator()
1761   {return expr;}
1762 }
1763
1764 Expression refPrimaryExpression(final Token reference) :
1765 {
1766   Expression expr;
1767   Expression expr2 = null;
1768   final Token identifier;
1769 }
1770 {
1771   identifier = <IDENTIFIER>
1772   {
1773     expr = new ConstantIdentifier(identifier);
1774   }
1775   (
1776     <STATICCLASSACCESS> expr2 = ClassIdentifier()
1777     {expr = new ClassAccess(expr,
1778                             expr2,
1779                             ClassAccess.STATIC);}
1780   )*
1781   [ expr2 = Arguments(expr) ]
1782   {
1783     if (expr2 == null) {
1784       if (reference != null) {
1785         ParseException e = generateParseException();
1786         errorMessage = "you cannot use a constant by reference";
1787         errorLevel   = ERROR;
1788         errorStart   = reference.sourceStart;
1789         errorEnd     = reference.sourceEnd;
1790         processParseExceptionDebug(e);
1791       }
1792       return expr;
1793     }
1794     return expr2;
1795   }
1796 |
1797   expr = VariableDeclaratorId()  //todo use the reference parameter ...
1798   [ expr = Arguments(expr) ]
1799   {return expr;}
1800 |
1801   token = <NEW>
1802   expr = ClassIdentifier()
1803   {
1804     int start;
1805     if (reference == null) {
1806       start = token.sourceStart;
1807     } else {
1808       start = reference.sourceStart;
1809     }
1810     expr = new ClassInstantiation(expr,
1811                                   reference != null,
1812                                   start);
1813   }
1814   [ expr = Arguments(expr) ]
1815   {return expr;}
1816 }
1817
1818 /**
1819  * An array declarator.
1820  * array(vars)
1821  * @return an array
1822  */
1823 ArrayInitializer ArrayDeclarator() :
1824 {
1825   final ArrayVariableDeclaration[] vars;
1826   final Token token;
1827 }
1828 {
1829   token = <ARRAY> vars = ArrayInitializer()
1830   {return new ArrayInitializer(vars,
1831                                token.sourceStart,
1832                                PHPParser.token.sourceEnd);}
1833 }
1834
1835 Expression ClassIdentifier():
1836 {
1837   final Expression expr;
1838   final Token token;
1839 }
1840 {
1841   token = <IDENTIFIER>          {return new ConstantIdentifier(token);}
1842 | expr = Type()                 {return expr;}
1843 | expr = VariableDeclaratorId() {return expr;}
1844 }
1845
1846 /**
1847  * Used by Variabledeclaratorid and primarysuffix
1848  */
1849 AbstractVariable VariableSuffix(final AbstractVariable prefix) :
1850 {
1851   Expression expression = null;
1852   final Token classAccessToken,lbrace,rbrace;
1853   Token token;
1854   int pos;
1855 }
1856 {
1857   classAccessToken = <CLASSACCESS>
1858   try {
1859     (
1860       lbrace = <LBRACE> expression = Expression() rbrace = <RBRACE>
1861                 {
1862                  expression = new Variable(expression,
1863                                            lbrace.sourceStart,
1864                                            rbrace.sourceEnd);
1865                 }
1866       |
1867         token = <IDENTIFIER>
1868         {expression = new ConstantIdentifier(token.image,token.sourceStart,token.sourceEnd);}
1869       |
1870         expression = Variable()
1871     )
1872   } catch (ParseException e) {
1873     errorMessage = "unexpected token : '"+ e.currentToken.next.image +"', function call or field access expected";
1874     errorLevel   = ERROR;
1875     errorStart = classAccessToken.sourceEnd +1;
1876     errorEnd   = classAccessToken.sourceEnd +1;
1877     processParseExceptionDebug(e);
1878   }
1879   {return new ClassAccess(prefix,
1880                           expression,
1881                           ClassAccess.NORMAL);}
1882 |
1883   token = <LBRACKET> {pos = token.sourceEnd+1;}
1884   [  expression = Expression() {pos = expression.sourceEnd+1;}
1885    | expression = Type()       {pos = expression.sourceEnd+1;}]  //Not good
1886   try {
1887     token = <RBRACKET>
1888     {pos = token.sourceEnd;}
1889   } catch (ParseException e) {
1890     errorMessage = "']' expected";
1891     errorLevel   = ERROR;
1892     errorStart = pos;
1893     errorEnd   = pos;
1894     processParseExceptionDebug(e);
1895   }
1896   {return new ArrayDeclarator(prefix,expression,pos);}
1897 |
1898   token = <LBRACE> {pos = token.sourceEnd+1;}
1899   [  expression = Expression() {pos = expression.sourceEnd+1;}
1900    | expression = Type()       {pos = expression.sourceEnd+1;}]  //Not good
1901   try {
1902     token = <RBRACE>
1903     {pos = token.sourceEnd;}
1904   } catch (ParseException e) {
1905     errorMessage = "']' expected";
1906     errorLevel   = ERROR;
1907     errorStart = pos;
1908     errorEnd   = pos;
1909     processParseExceptionDebug(e);
1910   }
1911   {return new ArrayDeclarator(prefix,expression,pos);}//todo : check braces here
1912 }
1913
1914 Literal Literal() :
1915 {
1916   final Token token;
1917 }
1918 {
1919   token = <INTEGER_LITERAL>        {return new NumberLiteral(token);}
1920 | token = <FLOATING_POINT_LITERAL> {return new NumberLiteral(token);}
1921 | token = <STRING_LITERAL>         {return new StringLiteral(token);}
1922 | token = <TRUE>                   {return new TrueLiteral(token);}
1923 | token = <FALSE>                  {return new FalseLiteral(token);}
1924 | token = <NULL>                   {return new NullLiteral(token);}
1925 }
1926
1927 FunctionCall Arguments(final Expression func) :
1928 {
1929 Expression[] args = null;
1930 final Token token;
1931 }
1932 {
1933   <LPAREN> [ args = ArgumentList() ]
1934   try {
1935     token = <RPAREN>
1936     {return new FunctionCall(func,args,token.sourceEnd);}
1937   } catch (ParseException e) {
1938     errorMessage = "unexpected token : '"+ e.currentToken.next.image +"', ')' expected to close the argument list";
1939     errorLevel   = ERROR;
1940     errorStart = args[args.length-1].sourceEnd+1;
1941     errorEnd   = args[args.length-1].sourceEnd+1;
1942     processParseExceptionDebug(e);
1943   }
1944   {return new FunctionCall(func,args,args[args.length-1].sourceEnd);}
1945 }
1946
1947 /**
1948  * An argument list is a list of arguments separated by comma :
1949  * argumentDeclaration() (, argumentDeclaration)*
1950  * @return an array of arguments
1951  */
1952 Expression[] ArgumentList() :
1953 {
1954 Expression arg;
1955 final ArrayList list = new ArrayList();
1956 int pos;
1957 Token token;
1958 }
1959 {
1960   arg = Expression()
1961   {list.add(arg);pos = arg.sourceEnd;}
1962   ( token = <COMMA> {pos = token.sourceEnd;}
1963       try {
1964         arg = Expression()
1965         {list.add(arg);
1966          pos = arg.sourceEnd;}
1967       } catch (ParseException e) {
1968         errorMessage = "unexpected token : '"+ e.currentToken.next.image +"'. An expression expected after a comma in argument list";
1969         errorLevel   = ERROR;
1970         errorStart   = pos+1;
1971         errorEnd     = pos+1;
1972         processParseException(e);
1973       }
1974    )*
1975    {
1976    final Expression[] arguments = new Expression[list.size()];
1977    list.toArray(arguments);
1978    return arguments;}
1979 }
1980
1981 /**
1982  * A Statement without break.
1983  * @return a statement
1984  */
1985 Statement StatementNoBreak() :
1986 {
1987   final Statement statement;
1988   Token token = null;
1989 }
1990 {
1991   LOOKAHEAD(2)
1992   statement = expressionStatement()     {return statement;}
1993 | LOOKAHEAD(1)
1994   statement = LabeledStatement()        {return statement;}
1995 | statement = Block()                   {return statement;}
1996 | statement = EmptyStatement()          {return statement;}
1997 | statement = SwitchStatement()         {return statement;}
1998 | statement = IfStatement()             {return statement;}
1999 | statement = WhileStatement()          {return statement;}
2000 | statement = DoStatement()             {return statement;}
2001 | statement = ForStatement()            {return statement;}
2002 | statement = ForeachStatement()        {return statement;}
2003 | statement = ContinueStatement()       {return statement;}
2004 | statement = ReturnStatement()         {return statement;}
2005 | statement = EchoStatement()           {return statement;}
2006 | [token=<AT>] statement = IncludeStatement()
2007   {if (token != null) {
2008     ((InclusionStatement)statement).silent = true;
2009     statement.sourceStart = token.sourceStart;
2010   }
2011   return statement;}
2012 | statement = StaticStatement()         {return statement;}
2013 | statement = GlobalStatement()         {return statement;}
2014 | statement = defineStatement()         {currentSegment.add((Outlineable)statement);return statement;}
2015 }
2016
2017 /**
2018  * A statement expression.
2019  * expression ;
2020  * @return an expression
2021  */
2022 Statement expressionStatement() :
2023 {
2024   final Statement statement;
2025   final Token token;
2026 }
2027 {
2028   statement = Expression()
2029   try {
2030     token = <SEMICOLON>
2031     {statement.sourceEnd = token.sourceEnd;}
2032   } catch (ParseException e) {
2033     if (e.currentToken.next.kind != PHPParserConstants.PHPEND) {
2034       errorMessage = "unexpected token : '"+ e.currentToken.next.image +"'. A ';' was expected";
2035       errorLevel   = ERROR;
2036       errorStart = statement.sourceEnd+1;
2037       errorEnd   = statement.sourceEnd+1;
2038       processParseExceptionDebug(e);
2039     }
2040   }
2041   {return statement;}
2042 }
2043
2044 Define defineStatement() :
2045 {
2046   Expression defineName,defineValue;
2047   final Token defineToken;
2048   Token token;
2049   int pos;
2050 }
2051 {
2052   defineToken = <DEFINE> {pos = defineToken.sourceEnd+1;}
2053   try {
2054     token = <LPAREN>
2055     {pos = token.sourceEnd+1;}
2056   } catch (ParseException e) {
2057     errorMessage = "unexpected token : '"+ e.currentToken.next.image +"', '(' expected";
2058     errorLevel   = ERROR;
2059     errorStart   = pos;
2060     errorEnd     = pos;
2061     processParseExceptionDebug(e);
2062   }
2063   try {
2064     defineName = Expression()
2065     {pos = defineName.sourceEnd+1;}
2066   } catch (ParseException e) {
2067     errorMessage = "unexpected token : '"+ e.currentToken.next.image +"', expression expected";
2068     errorLevel   = ERROR;
2069     errorStart   = pos;
2070     errorEnd     = pos;
2071     processParseExceptionDebug(e);
2072     defineName = new StringLiteral(SYNTAX_ERROR_CHAR,pos,pos);
2073   }
2074   try {
2075     token = <COMMA>
2076     {pos = defineName.sourceEnd+1;}
2077   } catch (ParseException e) {
2078     errorMessage = "unexpected token : '"+ e.currentToken.next.image +"', ',' expected";
2079     errorLevel   = ERROR;
2080     errorStart   = pos;
2081     errorEnd     = pos;
2082     processParseExceptionDebug(e);
2083   }
2084   try {
2085     defineValue = Expression()
2086     {pos = defineValue.sourceEnd+1;}
2087   } catch (ParseException e) {
2088     errorMessage = "unexpected token : '"+ e.currentToken.next.image +"', expression expected";
2089     errorLevel   = ERROR;
2090     errorStart   = pos;
2091     errorEnd     = pos;
2092     processParseExceptionDebug(e);
2093     defineValue = new StringLiteral(SYNTAX_ERROR_CHAR,pos,pos);
2094   }
2095   try {
2096     token = <RPAREN>
2097     {pos = token.sourceEnd+1;}
2098   } catch (ParseException e) {
2099     errorMessage = "unexpected token : '"+ e.currentToken.next.image +"', ')' expected";
2100     errorLevel   = ERROR;
2101     errorStart   = pos;
2102     errorEnd     = pos;
2103     processParseExceptionDebug(e);
2104   }
2105   {return new Define(currentSegment,
2106                      defineName,
2107                      defineValue,
2108                      defineToken.sourceStart,
2109                      pos);}
2110 }
2111
2112 /**
2113  * A Normal statement.
2114  */
2115 Statement Statement() :
2116 {
2117   final Statement statement;
2118 }
2119 {
2120   statement = StatementNoBreak() {return statement;}
2121 | statement = BreakStatement()   {return statement;}
2122 }
2123
2124 /**
2125  * An html block inside a php syntax.
2126  */
2127 HTMLBlock htmlBlock() :
2128 {
2129   final int startIndex = nodePtr;
2130   final AstNode[] blockNodes;
2131   final int nbNodes;
2132   final Token phpEnd;
2133 }
2134 {
2135   phpEnd = <PHPEND>
2136   {htmlStart = phpEnd.sourceEnd;}
2137   (phpEchoBlock())*
2138   try {
2139     (<PHPSTARTLONG> | <PHPSTARTSHORT>)
2140     {PHPParser.createNewHTMLCode();}
2141   } catch (ParseException e) {
2142     errorMessage = "unexpected end of file , '<?php' expected";
2143     errorLevel   = ERROR;
2144     errorStart   = SimpleCharStream.getPosition();
2145     errorEnd     = SimpleCharStream.getPosition();
2146     throw e;
2147   }
2148   {
2149   nbNodes    = nodePtr - startIndex;
2150   if (nbNodes == 0) {
2151     return null;
2152   }
2153   blockNodes = new AstNode[nbNodes];
2154   System.arraycopy(nodes,startIndex+1,blockNodes,0,nbNodes);
2155   nodePtr = startIndex;
2156   return new HTMLBlock(blockNodes);}
2157 }
2158
2159 /**
2160  * An include statement. It's "include" an expression;
2161  */
2162 InclusionStatement IncludeStatement() :
2163 {
2164   Expression expr;
2165   final int keyword;
2166   final InclusionStatement inclusionStatement;
2167   final Token token, token2;
2168   int pos;
2169 }
2170 {
2171       (  token = <REQUIRE>      {keyword = InclusionStatement.REQUIRE;pos=token.sourceEnd;}
2172        | token = <REQUIRE_ONCE> {keyword = InclusionStatement.REQUIRE_ONCE;pos=token.sourceEnd;}
2173        | token = <INCLUDE>      {keyword = InclusionStatement.INCLUDE;pos=token.sourceEnd;}
2174        | token = <INCLUDE_ONCE> {keyword = InclusionStatement.INCLUDE_ONCE;pos=token.sourceEnd;})
2175   try {
2176     expr = Expression()
2177     {pos = expr.sourceEnd;}
2178   } catch (ParseException e) {
2179     if (errorMessage != null) {
2180       throw e;
2181     }
2182     errorMessage = "unexpected token '"+ e.currentToken.next.image+"', expression expected";
2183     errorLevel   = ERROR;
2184     errorStart   = e.currentToken.next.sourceStart;
2185     errorEnd     = e.currentToken.next.sourceEnd;
2186     expr = new ConstantIdentifier(SYNTAX_ERROR_CHAR,pos,pos);
2187     processParseExceptionDebug(e);
2188   }
2189   try {
2190     token2 = <SEMICOLON>
2191     {pos=token2.sourceEnd;}
2192   } catch (ParseException e) {
2193     errorMessage = "unexpected token : '"+ e.currentToken.next.image +"'. A ';' was expected";
2194     errorLevel   = ERROR;
2195     errorStart   = e.currentToken.next.sourceStart;
2196     errorEnd     = e.currentToken.next.sourceEnd;
2197     processParseExceptionDebug(e);
2198   }
2199   {
2200    inclusionStatement = new InclusionStatement(currentSegment,
2201                                                keyword,
2202                                                expr,
2203                                                token.sourceStart,
2204                                                pos);
2205    currentSegment.add(inclusionStatement);
2206    return inclusionStatement;
2207   }
2208 }
2209
2210 PrintExpression PrintExpression() :
2211 {
2212   final Expression expr;
2213   final Token printToken;
2214 }
2215 {
2216   token = <PRINT> expr = Expression()
2217   {return new PrintExpression(expr,token.sourceStart,expr.sourceEnd);}
2218 }
2219
2220 ListExpression ListExpression() :
2221 {
2222   Expression expr = null;
2223   final Expression expression;
2224   final ArrayList list = new ArrayList();
2225   int pos;
2226   final Token listToken, rParen;
2227   Token token;
2228 }
2229 {
2230   listToken = <LIST> {pos = listToken.sourceEnd;}
2231   try {
2232     token = <LPAREN> {pos = token.sourceEnd;}
2233   } catch (ParseException e) {
2234     errorMessage = "unexpected token : '"+ e.currentToken.next.image +"', '(' expected";
2235     errorLevel   = ERROR;
2236     errorStart   = listToken.sourceEnd+1;
2237     errorEnd     = listToken.sourceEnd+1;
2238     processParseExceptionDebug(e);
2239   }
2240   [
2241     expr = VariableDeclaratorId()
2242     {list.add(expr);pos = expr.sourceEnd;}
2243   ]
2244   {if (expr == null) list.add(null);}
2245   (
2246     try {
2247       token = <COMMA>
2248       {pos = token.sourceEnd;}
2249     } catch (ParseException e) {
2250       errorMessage = "unexpected token : '"+ e.currentToken.next.image +"', ',' expected";
2251       errorLevel   = ERROR;
2252       errorStart   = pos+1;
2253       errorEnd     = pos+1;
2254       processParseExceptionDebug(e);
2255     }
2256     [expr = VariableDeclaratorId() {list.add(expr);pos = expr.sourceEnd;}]
2257   )*
2258   try {
2259     rParen = <RPAREN>
2260     {pos = rParen.sourceEnd;}
2261   } catch (ParseException e) {
2262     errorMessage = "unexpected token : '"+ e.currentToken.next.image +"', ')' expected";
2263     errorLevel   = ERROR;
2264     errorStart = pos+1;
2265     errorEnd   = pos+1;
2266       processParseExceptionDebug(e);
2267   }
2268   [ <ASSIGN> expression = Expression()
2269     {
2270     final AbstractVariable[] vars = new AbstractVariable[list.size()];
2271     list.toArray(vars);
2272     return new ListExpression(vars,
2273                               expression,
2274                               listToken.sourceStart,
2275                               expression.sourceEnd);}
2276   ]
2277   {
2278     final AbstractVariable[] vars = new AbstractVariable[list.size()];
2279     list.toArray(vars);
2280     return new ListExpression(vars,listToken.sourceStart,pos);}
2281 }
2282
2283 /**
2284  * An echo statement.
2285  * echo anyexpression (, otherexpression)*
2286  */
2287 EchoStatement EchoStatement() :
2288 {
2289   final ArrayList expressions = new ArrayList();
2290   Expression expr;
2291   Token token;
2292   Token token2 = null;
2293 }
2294 {
2295   token = <ECHO> expr = Expression()
2296   {expressions.add(expr);}
2297   (
2298     <COMMA> expr = Expression()
2299     {expressions.add(expr);}
2300   )*
2301   try {
2302     token2 = <SEMICOLON>
2303   } catch (ParseException e) {
2304     if (e.currentToken.next.kind != 4) {
2305       errorMessage = "';' expected after 'echo' statement";
2306       errorLevel   = ERROR;
2307       errorStart   = e.currentToken.sourceEnd;
2308       errorEnd     = e.currentToken.sourceEnd;
2309       processParseExceptionDebug(e);
2310     }
2311   }
2312   {
2313    final Expression[] exprs = new Expression[expressions.size()];
2314    expressions.toArray(exprs);
2315    if (token2 == null) {
2316      return new EchoStatement(exprs,token.sourceStart, exprs[exprs.length-1].sourceEnd);
2317    }
2318    return new EchoStatement(exprs,token.sourceStart, token2.sourceEnd);
2319    }
2320 }
2321
2322 GlobalStatement GlobalStatement() :
2323 {
2324    Variable expr;
2325    final ArrayList vars = new ArrayList();
2326    final GlobalStatement global;
2327    final Token token, token2;
2328    int pos;
2329 }
2330 {
2331   token = <GLOBAL>
2332     expr = Variable()
2333     {vars.add(expr);pos = expr.sourceEnd+1;}
2334   (<COMMA>
2335     expr = Variable()
2336     {vars.add(expr);pos = expr.sourceEnd+1;}
2337   )*
2338   try {
2339     token2 = <SEMICOLON>
2340     {pos = token2.sourceEnd+1;}
2341   } catch (ParseException e) {
2342     errorMessage = "unexpected token : '"+ e.currentToken.next.image +"'. a ';' was expected";
2343     errorLevel   = ERROR;
2344     errorStart = pos;
2345     errorEnd   = pos;
2346     processParseExceptionDebug(e);
2347   }
2348     {
2349     final Variable[] variables = new Variable[vars.size()];
2350     vars.toArray(variables);
2351     global = new GlobalStatement(currentSegment,
2352                                  variables,
2353                                  token.sourceStart,
2354                                  pos);
2355     currentSegment.add(global);
2356     return global;}
2357 }
2358
2359 StaticStatement StaticStatement() :
2360 {
2361   final ArrayList vars = new ArrayList();
2362   VariableDeclaration expr;
2363   final Token token, token2;
2364   int pos;
2365 }
2366 {
2367   token = <STATIC> expr = VariableDeclarator() {vars.add(expr);pos = expr.sourceEnd+1;}
2368   (
2369     <COMMA> expr = VariableDeclarator() {vars.add(expr);pos = expr.sourceEnd+1;}
2370   )*
2371   try {
2372     token2 = <SEMICOLON>
2373     {pos = token2.sourceEnd+1;}
2374   } catch (ParseException e) {
2375     errorMessage = "unexpected token : '"+ e.currentToken.next.image +"'. a ';' was expected";
2376     errorLevel   = ERROR;
2377     errorStart = pos;
2378     errorEnd   = pos;
2379     processParseException(e);
2380   }
2381     {
2382     final VariableDeclaration[] variables = new VariableDeclaration[vars.size()];
2383     vars.toArray(variables);
2384     return new StaticStatement(variables,
2385                                token.sourceStart,
2386                                pos);}
2387 }
2388
2389 LabeledStatement LabeledStatement() :
2390 {
2391   final Token label;
2392   final Statement statement;
2393 }
2394 {
2395   label = <IDENTIFIER> <COLON> statement = Statement()
2396   {return new LabeledStatement(label.image,statement,label.sourceStart,statement.sourceEnd);}
2397 }
2398
2399 /**
2400  * A Block is
2401  * {
2402  * statements
2403  * }.
2404  * @return a block
2405  */
2406 Block Block() :
2407 {
2408   final ArrayList list = new ArrayList();
2409   Statement statement;
2410   final Token token, token2;
2411   int pos,start;
2412 }
2413 {
2414   try {
2415     token = <LBRACE>
2416     {pos = token.sourceEnd+1;start=token.sourceStart;}
2417   } catch (ParseException e) {
2418     errorMessage = "'{' expected";
2419     errorLevel   = ERROR;
2420     pos = PHPParser.token.sourceEnd+1;
2421     start=pos;
2422     errorStart = pos;
2423     errorEnd   = pos;
2424     processParseExceptionDebug(e);
2425   }
2426   ( statement = BlockStatement() {list.add(statement);pos = statement.sourceEnd+1;}
2427   | statement = htmlBlock()      {if (statement != null) {
2428                                     list.add(statement);
2429                                     pos = statement.sourceEnd+1;
2430                                   }
2431                                   pos = PHPParser.token.sourceEnd+1;
2432                                  }
2433   )*
2434   try {
2435     token2 = <RBRACE>
2436     {pos = token2.sourceEnd+1;}
2437   } catch (ParseException e) {
2438     errorMessage = "unexpected token : '"+ e.currentToken.image +"', '}' expected";
2439     errorLevel   = ERROR;
2440     errorStart = pos;
2441     errorEnd   = pos;
2442     processParseExceptionDebug(e);
2443   }
2444   {
2445   final Statement[] statements = new Statement[list.size()];
2446   list.toArray(statements);
2447   return new Block(statements,start,pos);}
2448 }
2449
2450 Statement BlockStatement() :
2451 {
2452   final Statement statement;
2453 }
2454 {
2455   try {
2456     statement = Statement()         {if (phpDocument == currentSegment) pushOnAstNodes(statement);
2457                                      return statement;}
2458   } catch (ParseException e) {
2459     errorMessage = "unexpected token : '"+ e.currentToken.image +"', a statement was expected";
2460     errorLevel   = ERROR;
2461     errorStart = e.currentToken.sourceStart;
2462     errorEnd   = e.currentToken.sourceEnd;
2463     throw e;
2464   }
2465 | statement = ClassDeclaration()  {return statement;}
2466 | statement = MethodDeclaration() {if (phpDocument == currentSegment) pushOnAstNodes(statement);
2467                                    currentSegment.add((MethodDeclaration) statement);
2468                                    ((MethodDeclaration) statement).analyzeCode();
2469                                    return statement;}
2470 }
2471
2472 /**
2473  * A Block statement that will not contain any 'break'
2474  */
2475 Statement BlockStatementNoBreak() :
2476 {
2477   final Statement statement;
2478 }
2479 {
2480   statement = StatementNoBreak()  {return statement;}
2481 | statement = ClassDeclaration()  {return statement;}
2482 | statement = MethodDeclaration() {currentSegment.add((MethodDeclaration) statement);
2483                                    ((MethodDeclaration) statement).analyzeCode();
2484                                    return statement;}
2485 }
2486
2487 /**
2488  * used only by ForInit()
2489  */
2490 Expression[] LocalVariableDeclaration() :
2491 {
2492   final ArrayList list = new ArrayList();
2493   Expression var;
2494 }
2495 {
2496   var = Expression()
2497   {list.add(var);}
2498   ( <COMMA> var = Expression() {list.add(var);})*
2499   {
2500     final Expression[] vars = new Expression[list.size()];
2501     list.toArray(vars);
2502     return vars;
2503   }
2504 }
2505
2506 /**
2507  * used only by LocalVariableDeclaration().
2508  */
2509 VariableDeclaration LocalVariableDeclarator() :
2510 {
2511   final Variable varName;
2512   Expression initializer = null;
2513 }
2514 {
2515   varName = Variable() [ <ASSIGN> initializer = Expression() ]
2516   {
2517    if (initializer == null) {
2518     return new VariableDeclaration(currentSegment,
2519                                    varName,
2520                                    varName.sourceStart,
2521                                    varName.sourceEnd);
2522    }
2523     return new VariableDeclaration(currentSegment,
2524                                    varName,
2525                                    initializer,
2526                                    VariableDeclaration.EQUAL,
2527                                    varName.sourceStart);
2528   }
2529 }
2530
2531 EmptyStatement EmptyStatement() :
2532 {
2533   final Token token;
2534 }
2535 {
2536   token = <SEMICOLON>
2537   {return new EmptyStatement(token.sourceStart,token.sourceEnd);}
2538 }
2539
2540 /**
2541  * used only by StatementExpressionList() which is used only by ForInit() and ForStatement()
2542  */
2543 Expression StatementExpression() :
2544 {
2545   final Expression expr;
2546   final Token operator;
2547 }
2548 {
2549   expr = PreIncDecExpression() {return expr;}
2550 |
2551   expr = PrimaryExpression()
2552   [ operator = <PLUS_PLUS> {return new PostfixedUnaryExpression(expr,
2553                                                                 OperatorIds.PLUS_PLUS,
2554                                                                 operator.sourceEnd);}
2555   | operator = <MINUS_MINUS> {return new PostfixedUnaryExpression(expr,
2556                                                                   OperatorIds.MINUS_MINUS,
2557                                                                   operator.sourceEnd);}
2558   ]
2559   {return expr;}
2560 }
2561
2562 SwitchStatement SwitchStatement() :
2563 {
2564   Expression variable;
2565   final AbstractCase[] cases;
2566   final Token switchToken,lparenToken,rparenToken;
2567   int pos;
2568 }
2569 {
2570   switchToken = <SWITCH> {pos = switchToken.sourceEnd+1;}
2571   try {
2572     lparenToken = <LPAREN>
2573     {pos = lparenToken.sourceEnd+1;}
2574   } catch (ParseException e) {
2575     errorMessage = "'(' expected after 'switch'";
2576     errorLevel   = ERROR;
2577     errorStart = pos;
2578     errorEnd   = pos;
2579     processParseExceptionDebug(e);
2580   }
2581   try {
2582     variable = Expression() {pos = variable.sourceEnd+1;}
2583   } catch (ParseException e) {
2584     if (errorMessage != null) {
2585       throw e;
2586     }
2587     errorMessage = "expression expected";
2588     errorLevel   = ERROR;
2589     errorStart = pos;
2590     errorEnd   = pos;
2591     processParseExceptionDebug(e);
2592     variable = new ConstantIdentifier(SYNTAX_ERROR_CHAR,pos,pos);
2593   }
2594   try {
2595     rparenToken = <RPAREN> {pos = rparenToken.sourceEnd+1;}
2596   } catch (ParseException e) {
2597     errorMessage = "')' expected";
2598     errorLevel   = ERROR;
2599     errorStart = pos;
2600     errorEnd   = pos;
2601     processParseExceptionDebug(e);
2602   }
2603   (  cases = switchStatementBrace()
2604    | cases = switchStatementColon(switchToken.sourceStart, switchToken.sourceEnd))
2605   {return new SwitchStatement(variable,
2606                               cases,
2607                               switchToken.sourceStart,
2608                               PHPParser.token.sourceEnd);}
2609 }
2610
2611 AbstractCase[] switchStatementBrace() :
2612 {
2613   AbstractCase cas;
2614   final ArrayList cases = new ArrayList();
2615   Token token;
2616   int pos;
2617 }
2618 {
2619   token = <LBRACE> {pos = token.sourceEnd;}
2620  ( cas = switchLabel0() {cases.add(cas);pos = cas.sourceEnd;})*
2621   try {
2622     token = <RBRACE>
2623     {pos = token.sourceEnd;}
2624   } catch (ParseException e) {
2625     errorMessage = "'}' expected";
2626     errorLevel   = ERROR;
2627     errorStart = pos+1;
2628     errorEnd   = pos+1;
2629     processParseExceptionDebug(e);
2630   }
2631   {
2632     final AbstractCase[] abcase = new AbstractCase[cases.size()];
2633     cases.toArray(abcase);
2634     return abcase;
2635   }
2636 }
2637
2638 /**
2639  * A Switch statement with : ... endswitch;
2640  * @param start the begin offset of the switch
2641  * @param end the end offset of the switch
2642  */
2643 AbstractCase[] switchStatementColon(final int start, final int end) :
2644 {
2645   AbstractCase cas;
2646   final ArrayList cases = new ArrayList();
2647   Token token;
2648   int pos;
2649 }
2650 {
2651   token = <COLON> {pos = token.sourceEnd;}
2652   {try {
2653   setMarker(fileToParse,
2654             "Ugly syntax detected, you should switch () {...} instead of switch (): ... enswitch;",
2655             start,
2656             end,
2657             INFO,
2658             "Line " + token.beginLine);
2659   } catch (CoreException e) {
2660     PHPeclipsePlugin.log(e);
2661   }}
2662   ( cas = switchLabel0() {cases.add(cas);pos = cas.sourceEnd;})*
2663   try {
2664     token = <ENDSWITCH> {pos = token.sourceEnd;}
2665   } catch (ParseException e) {
2666     errorMessage = "'endswitch' expected";
2667     errorLevel   = ERROR;
2668     errorStart = pos+1;
2669     errorEnd   = pos+1;
2670     processParseExceptionDebug(e);
2671   }
2672   try {
2673     token = <SEMICOLON> {pos = token.sourceEnd;}
2674   } catch (ParseException e) {
2675     errorMessage = "';' expected after 'endswitch' keyword";
2676     errorLevel   = ERROR;
2677     errorStart = pos+1;
2678     errorEnd   = pos+1;
2679     processParseExceptionDebug(e);
2680   }
2681   {
2682     final AbstractCase[] abcase = new AbstractCase[cases.size()];
2683     cases.toArray(abcase);
2684     return abcase;
2685   }
2686 }
2687
2688 AbstractCase switchLabel0() :
2689 {
2690   final Expression expr;
2691   Statement statement;
2692   final ArrayList stmts = new ArrayList();
2693   final Token token = PHPParser.token;
2694 }
2695 {
2696   expr = SwitchLabel()
2697   ( statement = BlockStatementNoBreak() {stmts.add(statement);}
2698   | statement = htmlBlock()             {if (statement != null) {stmts.add(statement);}}
2699   | statement = BreakStatement()        {stmts.add(statement);})*
2700   //[ statement = BreakStatement()        {stmts.add(statement);}]
2701   {
2702     final int listSize = stmts.size();
2703     final Statement[] stmtsArray = new Statement[listSize];
2704     stmts.toArray(stmtsArray);
2705     if (expr == null) {//it's a default
2706       return new DefaultCase(stmtsArray,token.sourceStart,stmtsArray[listSize-1].sourceEnd);
2707     }
2708     if (listSize != 0) {
2709       return new Case(expr,stmtsArray,expr.sourceStart,stmtsArray[listSize-1].sourceEnd);
2710     } else {
2711       return new Case(expr,stmtsArray,expr.sourceStart,expr.sourceEnd);
2712     }
2713   }
2714 }
2715
2716 /**
2717  * A SwitchLabel.
2718  * case Expression() :
2719  * default :
2720  * @return the if it was a case and null if not
2721  */
2722 Expression SwitchLabel() :
2723 {
2724   final Expression expr;
2725 }
2726 {
2727   token = <CASE>
2728   try {
2729     expr = Expression()
2730   } catch (ParseException e) {
2731     if (errorMessage != null) throw e;
2732     errorMessage = "expression expected after 'case' keyword";
2733     errorLevel   = ERROR;
2734     errorStart = token.sourceEnd +1;
2735     errorEnd   = token.sourceEnd +1;
2736     throw e;
2737   }
2738   try {
2739     token = <COLON>
2740     {return expr;}
2741   } catch (ParseException e) {
2742     errorMessage = "':' expected after case expression";
2743     errorLevel   = ERROR;
2744     errorStart = expr.sourceEnd+1;
2745     errorEnd   = expr.sourceEnd+1;
2746     processParseExceptionDebug(e);
2747   }
2748 |
2749   token = <_DEFAULT>
2750   try {
2751     <COLON>
2752     {return null;}
2753   } catch (ParseException e) {
2754     errorMessage = "':' expected after 'default' keyword";
2755     errorLevel   = ERROR;
2756     errorStart = token.sourceEnd+1;
2757     errorEnd   = token.sourceEnd+1;
2758     processParseExceptionDebug(e);
2759   }
2760 }
2761
2762 Break BreakStatement() :
2763 {
2764   Expression expression = null;
2765   final Token token, token2;
2766   int pos;
2767 }
2768 {
2769   token = <BREAK> {pos = token.sourceEnd+1;}
2770   [ expression = Expression() {pos = expression.sourceEnd+1;}]
2771   try {
2772     token2 = <SEMICOLON>
2773     {pos = token2.sourceEnd;}
2774   } catch (ParseException e) {
2775     errorMessage = "';' expected after 'break' keyword";
2776     errorLevel   = ERROR;
2777     errorStart = pos;
2778     errorEnd   = pos;
2779     processParseExceptionDebug(e);
2780   }
2781   {return new Break(expression, token.sourceStart, pos);}
2782 }
2783
2784 IfStatement IfStatement() :
2785 {
2786   final Expression condition;
2787   final IfStatement ifStatement;
2788   Token token;
2789 }
2790 {
2791   token = <IF> condition = Condition("if")
2792   ifStatement = IfStatement0(condition,token.sourceStart,token.sourceEnd)
2793   {return ifStatement;}
2794 }
2795
2796
2797 Expression Condition(final String keyword) :
2798 {
2799   final Expression condition;
2800 }
2801 {
2802   try {
2803     <LPAREN>
2804   } catch (ParseException e) {
2805     errorMessage = "'(' expected after " + keyword + " keyword";
2806     errorLevel   = ERROR;
2807     errorStart = PHPParser.token.sourceEnd + 1;
2808     errorEnd   = PHPParser.token.sourceEnd + 1;
2809     processParseExceptionDebug(e);
2810   }
2811   condition = Expression()
2812   try {
2813      <RPAREN>
2814   } catch (ParseException e) {
2815     errorMessage = "')' expected after " + keyword + " keyword";
2816     errorLevel   = ERROR;
2817     errorStart = condition.sourceEnd+1;
2818     errorEnd   = condition.sourceEnd+1;
2819     processParseExceptionDebug(e);
2820   }
2821   {return condition;}
2822 }
2823
2824 IfStatement IfStatement0(final Expression condition, final int start,final int end) :
2825 {
2826   Statement statement;
2827   final Statement stmt;
2828   final Statement[] statementsArray;
2829   ElseIf elseifStatement;
2830   Else elseStatement = null;
2831   final ArrayList stmts;
2832   final ArrayList elseIfList = new ArrayList();
2833   final ElseIf[] elseIfs;
2834   int pos = SimpleCharStream.getPosition();
2835   final int endStatements;
2836 }
2837 {
2838   <COLON>
2839   {stmts = new ArrayList();}
2840   (  statement = Statement() {stmts.add(statement);}
2841    | statement = htmlBlock() {if (statement != null) {stmts.add(statement);}})*
2842    {endStatements = SimpleCharStream.getPosition();}
2843    (elseifStatement = ElseIfStatementColon() {elseIfList.add(elseifStatement);})*
2844    [elseStatement = ElseStatementColon()]
2845
2846   {try {
2847   setMarker(fileToParse,
2848             "Ugly syntax detected, you should if () {...} instead of if (): ... endif;",
2849             start,
2850             end,
2851             INFO,
2852             "Line " + token.beginLine);
2853   } catch (CoreException e) {
2854     PHPeclipsePlugin.log(e);
2855   }}
2856   try {
2857     <ENDIF>
2858   } catch (ParseException e) {
2859     errorMessage = "'endif' expected";
2860     errorLevel   = ERROR;
2861     errorStart = SimpleCharStream.getPosition() - e.currentToken.next.image.length() + 1;
2862     errorEnd   = SimpleCharStream.getPosition() + 1;
2863     throw e;
2864   }
2865   try {
2866     <SEMICOLON>
2867   } catch (ParseException e) {
2868     errorMessage = "';' expected after 'endif' keyword";
2869     errorLevel   = ERROR;
2870     errorStart = SimpleCharStream.getPosition() - e.currentToken.next.image.length() + 1;
2871     errorEnd   = SimpleCharStream.getPosition() + 1;
2872     throw e;
2873   }
2874     {
2875     elseIfs = new ElseIf[elseIfList.size()];
2876     elseIfList.toArray(elseIfs);
2877     if (stmts.size() == 1) {
2878       return new IfStatement(condition,
2879                              (Statement) stmts.get(0),
2880                               elseIfs,
2881                               elseStatement,
2882                               pos,
2883                               SimpleCharStream.getPosition());
2884     } else {
2885       statementsArray = new Statement[stmts.size()];
2886       stmts.toArray(statementsArray);
2887       return new IfStatement(condition,
2888                              new Block(statementsArray,pos,endStatements),
2889                              elseIfs,
2890                              elseStatement,
2891                              pos,
2892                              SimpleCharStream.getPosition());
2893     }
2894     }
2895
2896 |
2897   (stmt = Statement() | stmt = htmlBlock())
2898   ( LOOKAHEAD(1) elseifStatement = ElseIfStatement() {elseIfList.add(elseifStatement);})*
2899   [ LOOKAHEAD(1)
2900     <ELSE>
2901     try {
2902       {pos = SimpleCharStream.getPosition();}
2903       statement = Statement()
2904       {elseStatement = new Else(statement,pos,SimpleCharStream.getPosition());}
2905     } catch (ParseException e) {
2906       if (errorMessage != null) {
2907         throw e;
2908       }
2909       errorMessage = "unexpected token '"+e.currentToken.next.image+"', a statement was expected";
2910       errorLevel   = ERROR;
2911       errorStart = SimpleCharStream.getPosition() - e.currentToken.next.image.length() + 1;
2912       errorEnd   = SimpleCharStream.getPosition() + 1;
2913       throw e;
2914     }
2915   ]
2916   {
2917     elseIfs = new ElseIf[elseIfList.size()];
2918     elseIfList.toArray(elseIfs);
2919     return new IfStatement(condition,
2920                            stmt,
2921                            elseIfs,
2922                            elseStatement,
2923                            pos,
2924                            SimpleCharStream.getPosition());}
2925 }
2926
2927 ElseIf ElseIfStatementColon() :
2928 {
2929   final Expression condition;
2930   Statement statement;
2931   final ArrayList list = new ArrayList();
2932   final Token elseifToken;
2933 }
2934 {
2935   elseifToken = <ELSEIF> condition = Condition("elseif")
2936   <COLON> (  statement = Statement() {list.add(statement);}
2937            | statement = htmlBlock() {if (statement != null) {list.add(statement);}})*
2938   {
2939   final int sizeList = list.size();
2940   final Statement[] stmtsArray = new Statement[sizeList];
2941   list.toArray(stmtsArray);
2942   return new ElseIf(condition,stmtsArray ,
2943                     elseifToken.sourceStart,
2944                     stmtsArray[sizeList-1].sourceEnd);}
2945 }
2946
2947 Else ElseStatementColon() :
2948 {
2949   Statement statement;
2950   final ArrayList list = new ArrayList();
2951   final Token elseToken;
2952 }
2953 {
2954   elseToken = <ELSE> <COLON> (  statement = Statement() {list.add(statement);}
2955                   | statement = htmlBlock() {if (statement != null) {list.add(statement);}})*
2956   {
2957   final int sizeList = list.size();
2958   final Statement[] stmtsArray = new Statement[sizeList];
2959   list.toArray(stmtsArray);
2960   return new Else(stmtsArray,elseToken.sourceStart,stmtsArray[sizeList-1].sourceEnd);}
2961 }
2962
2963 ElseIf ElseIfStatement() :
2964 {
2965   final Expression condition;
2966   //final Statement statement;
2967   final Token elseifToken;
2968   final Statement[] statement = new Statement[1];
2969 }
2970 {
2971   elseifToken = <ELSEIF> condition = Condition("elseif") statement[0] = Statement()
2972   {
2973   return new ElseIf(condition,statement,elseifToken.sourceStart,statement[0].sourceEnd);}
2974 }
2975
2976 WhileStatement WhileStatement() :
2977 {
2978   final Expression condition;
2979   final Statement action;
2980   final Token whileToken;
2981 }
2982 {
2983   whileToken = <WHILE>
2984     condition = Condition("while")
2985     action    = WhileStatement0(whileToken.sourceStart,whileToken.sourceEnd)
2986     {return new WhileStatement(condition,action,whileToken.sourceStart,action.sourceEnd);}
2987 }
2988
2989 Statement WhileStatement0(final int start, final int end) :
2990 {
2991   Statement statement;
2992   final ArrayList stmts = new ArrayList();
2993   final int pos = SimpleCharStream.getPosition();
2994 }
2995 {
2996   <COLON> (statement = Statement() {stmts.add(statement);})*
2997   {try {
2998   setMarker(fileToParse,
2999             "Ugly syntax detected, you should while () {...} instead of while (): ... endwhile;",
3000             start,
3001             end,
3002             INFO,
3003             "Line " + token.beginLine);
3004   } catch (CoreException e) {
3005     PHPeclipsePlugin.log(e);
3006   }}
3007   try {
3008     <ENDWHILE>
3009   } catch (ParseException e) {
3010     errorMessage = "'endwhile' expected";
3011     errorLevel   = ERROR;
3012     errorStart = SimpleCharStream.getPosition() - e.currentToken.next.image.length() + 1;
3013     errorEnd   = SimpleCharStream.getPosition() + 1;
3014     throw e;
3015   }
3016   try {
3017     <SEMICOLON>
3018     {
3019     final Statement[] stmtsArray = new Statement[stmts.size()];
3020     stmts.toArray(stmtsArray);
3021     return new Block(stmtsArray,pos,SimpleCharStream.getPosition());}
3022   } catch (ParseException e) {
3023     errorMessage = "';' expected after 'endwhile' keyword";
3024     errorLevel   = ERROR;
3025     errorStart = SimpleCharStream.getPosition() - e.currentToken.next.image.length() + 1;
3026     errorEnd   = SimpleCharStream.getPosition() + 1;
3027     throw e;
3028   }
3029 |
3030   statement = Statement()
3031   {return statement;}
3032 }
3033
3034 DoStatement DoStatement() :
3035 {
3036   final Statement action;
3037   final Expression condition;
3038   final Token token;
3039   Token token2 = null;
3040 }
3041 {
3042   token = <DO> action = Statement() <WHILE> condition = Condition("while")
3043   try {
3044     token2 = <SEMICOLON>
3045   } catch (ParseException e) {
3046     errorMessage = "unexpected token : '"+ e.currentToken.next.image +"'. A ';' was expected";
3047     errorLevel   = ERROR;
3048     errorStart = condition.sourceEnd+1;
3049     errorEnd   = condition.sourceEnd+1;
3050     processParseExceptionDebug(e);
3051   }
3052   {
3053     if (token2 == null) {
3054       return new DoStatement(condition,action,token.sourceStart,condition.sourceEnd);
3055     }
3056     return new DoStatement(condition,action,token.sourceStart,token2.sourceEnd);
3057   }
3058 }
3059
3060 ForeachStatement ForeachStatement() :
3061 {
3062   Statement statement = null;
3063   Expression expression = null;
3064   ArrayVariableDeclaration variable = null;
3065   Token foreachToken;
3066   Token lparenToken = null;
3067   Token asToken = null;
3068   Token rparenToken = null;
3069   int pos;
3070 }
3071 {
3072   foreachToken = <FOREACH>
3073   try {
3074     lparenToken = <LPAREN>
3075     {pos = lparenToken.sourceEnd+1;}
3076   } catch (ParseException e) {
3077     errorMessage = "'(' expected after 'foreach' keyword";
3078     errorLevel   = ERROR;
3079     errorStart = foreachToken.sourceEnd+1;
3080     errorEnd   = foreachToken.sourceEnd+1;
3081     processParseExceptionDebug(e);
3082     {pos = foreachToken.sourceEnd+1;}
3083   }
3084   try {
3085     expression = Expression()
3086     {pos = expression.sourceEnd+1;}
3087   } catch (ParseException e) {
3088     errorMessage = "variable expected";
3089     errorLevel   = ERROR;
3090     errorStart = pos;
3091     errorEnd   = pos;
3092     processParseExceptionDebug(e);
3093   }
3094   try {
3095     asToken = <AS>
3096     {pos = asToken.sourceEnd+1;}
3097   } catch (ParseException e) {
3098     errorMessage = "'as' expected";
3099     errorLevel   = ERROR;
3100     errorStart = pos;
3101     errorEnd   = pos;
3102     processParseExceptionDebug(e);
3103   }
3104   try {
3105     variable = ArrayVariable()
3106     {pos = variable.sourceEnd+1;}
3107   } catch (ParseException e) {
3108     if (errorMessage != null) throw e;
3109     errorMessage = "variable expected";
3110     errorLevel   = ERROR;
3111     errorStart = pos;
3112     errorEnd   = pos;
3113     processParseExceptionDebug(e);
3114   }
3115   try {
3116     rparenToken = <RPAREN>
3117     {pos = rparenToken.sourceEnd+1;}
3118   } catch (ParseException e) {
3119     errorMessage = "')' expected after 'foreach' keyword";
3120     errorLevel   = ERROR;
3121     errorStart = pos;
3122     errorEnd   = pos;
3123     processParseExceptionDebug(e);
3124   }
3125   try {
3126     statement = Statement()
3127     {pos = rparenToken.sourceEnd+1;}
3128   } catch (ParseException e) {
3129     if (errorMessage != null) throw e;
3130     errorMessage = "statement expected";
3131     errorLevel   = ERROR;
3132     errorStart = pos;
3133     errorEnd   = pos;
3134     processParseExceptionDebug(e);
3135   }
3136   {return new ForeachStatement(expression,
3137                                variable,
3138                                statement,
3139                                foreachToken.sourceStart,
3140                                statement.sourceEnd);}
3141
3142 }
3143
3144 /**
3145  * a for declaration.
3146  * @return a node representing the for statement
3147  */
3148 ForStatement ForStatement() :
3149 {
3150 final Token token,tokenEndFor,token2,tokenColon;
3151 int pos;
3152 Expression[] initializations = null;
3153 Expression condition = null;
3154 Expression[] increments = null;
3155 Statement action;
3156 final ArrayList list = new ArrayList();
3157 }
3158 {
3159   token = <FOR>
3160   try {
3161     <LPAREN>
3162   } catch (ParseException e) {
3163     errorMessage = "'(' expected after 'for' keyword";
3164     errorLevel   = ERROR;
3165     errorStart = token.sourceEnd;
3166     errorEnd   = token.sourceEnd +1;
3167     processParseExceptionDebug(e);
3168   }
3169      [ initializations = ForInit() ] <SEMICOLON>
3170      [ condition = Expression() ] <SEMICOLON>
3171      [ increments = StatementExpressionList() ] <RPAREN>
3172     (
3173       action = Statement()
3174       {return new ForStatement(initializations,
3175                                condition,
3176                                increments,
3177                                action,
3178                                token.sourceStart,
3179                                action.sourceEnd);}
3180     |
3181       tokenColon = <COLON> {pos = tokenColon.sourceEnd+1;}
3182       (action = Statement() {list.add(action);pos = action.sourceEnd+1;})*
3183       {
3184         try {
3185         setMarker(fileToParse,
3186                   "Ugly syntax detected, you should for () {...} instead of for (): ... endfor;",
3187                   token.sourceStart,
3188                   token.sourceEnd,
3189                   INFO,
3190                   "Line " + token.beginLine);
3191         } catch (CoreException e) {
3192           PHPeclipsePlugin.log(e);
3193         }
3194       }
3195       try {
3196         tokenEndFor = <ENDFOR>
3197         {pos = tokenEndFor.sourceEnd+1;}
3198       } catch (ParseException e) {
3199         errorMessage = "'endfor' expected";
3200         errorLevel   = ERROR;
3201         errorStart = pos;
3202         errorEnd   = pos;
3203         processParseExceptionDebug(e);
3204       }
3205       try {
3206         token2 = <SEMICOLON>
3207         {pos = token2.sourceEnd+1;}
3208       } catch (ParseException e) {
3209         errorMessage = "';' expected after 'endfor' keyword";
3210         errorLevel   = ERROR;
3211         errorStart = pos;
3212         errorEnd   = pos;
3213         processParseExceptionDebug(e);
3214       }
3215       {
3216       final Statement[] stmtsArray = new Statement[list.size()];
3217       list.toArray(stmtsArray);
3218       return new ForStatement(initializations,
3219                               condition,
3220                               increments,
3221                               new Block(stmtsArray,
3222                                         stmtsArray[0].sourceStart,
3223                                         stmtsArray[stmtsArray.length-1].sourceEnd),
3224                               token.sourceStart,
3225                               pos);}
3226     )
3227 }
3228
3229 Expression[] ForInit() :
3230 {
3231   final Expression[] exprs;
3232 }
3233 {
3234   LOOKAHEAD(LocalVariableDeclaration())
3235   exprs = LocalVariableDeclaration()
3236   {return exprs;}
3237 |
3238   exprs = StatementExpressionList()
3239   {return exprs;}
3240 }
3241
3242 Expression[] StatementExpressionList() :
3243 {
3244   final ArrayList list = new ArrayList();
3245   final Expression expr;
3246 }
3247 {
3248   expr = Expression()   {list.add(expr);}
3249   (<COMMA> Expression() {list.add(expr);})*
3250   {
3251     final Expression[] exprsArray = new Expression[list.size()];
3252     list.toArray(exprsArray);
3253     return exprsArray;
3254   }
3255 }
3256
3257 Continue ContinueStatement() :
3258 {
3259   Expression expr = null;
3260   final Token token;
3261   Token token2 = null;
3262 }
3263 {
3264   token = <CONTINUE> [ expr = Expression() ]
3265   try {
3266     token2 = <SEMICOLON>
3267   } catch (ParseException e) {
3268     errorMessage = "';' expected after 'continue' statement";
3269     errorLevel   = ERROR;
3270     if (expr == null) {
3271       errorStart = token.sourceEnd+1;
3272       errorEnd   = token.sourceEnd+1;
3273     } else {
3274       errorStart = expr.sourceEnd+1;
3275       errorEnd   = expr.sourceEnd+1;
3276     }
3277     processParseExceptionDebug(e);
3278   }
3279   {
3280     if (token2 == null) {
3281       if (expr == null) {
3282         return new Continue(expr,token.sourceStart,token.sourceEnd);
3283       }
3284       return new Continue(expr,token.sourceStart,expr.sourceEnd);
3285     }
3286     return new Continue(expr,token.sourceStart,token2.sourceEnd);
3287   }
3288 }
3289
3290 ReturnStatement ReturnStatement() :
3291 {
3292   Expression expr = null;
3293   final Token token;
3294   Token token2 = null;
3295 }
3296 {
3297   token = <RETURN> [ expr = Expression() ]
3298   try {
3299     token2 = <SEMICOLON>
3300   } catch (ParseException e) {
3301     errorMessage = "';' expected after 'return' statement";
3302     errorLevel   = ERROR;
3303     if (expr == null) {
3304       errorStart = token.sourceEnd+1;
3305       errorEnd   = token.sourceEnd+1;
3306     } else {
3307       errorStart = expr.sourceEnd+1;
3308       errorEnd   = expr.sourceEnd+1;
3309     }
3310     processParseExceptionDebug(e);
3311   }
3312   {
3313     if (token2 == null) {
3314       if (expr == null) {
3315         return new ReturnStatement(expr,token.sourceStart,token.sourceEnd);
3316       }
3317       return new ReturnStatement(expr,token.sourceStart,expr.sourceEnd);
3318     }
3319     return new ReturnStatement(expr,token.sourceStart,token2.sourceEnd);
3320   }
3321 }
3322