35e1229d835746a1eb2bc61a1d4a2f43d30038de
[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 = false;
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_2> | <STRING_3>)>
593 //|   <STRING_1: "\"" ( ~["\"","\\"] | "\\" ~[] )* "\"">
594 |   <STRING_2: "'"  ( ~["'","\\"]  | "\\" ~[] )* "'">
595 |   <STRING_3: "`"  ( ~["`","\\"]  | "\\" ~[] )* "`">
596 }
597
598 <IN_STRING,DOLLAR_IN_STRING> SKIP :
599 {
600   <ESCAPED : ("\\" ~[])> : IN_STRING
601 }
602
603 <PHPPARSING> TOKEN :
604 {
605   <DOUBLEQUOTE : "\""> : IN_STRING
606 }
607
608
609 <IN_STRING> TOKEN :
610 {
611   <DOLLARS : "$"> : DOLLAR_IN_STRING
612 }
613
614 <IN_STRING,DOLLAR_IN_STRING> TOKEN :
615 {
616   <DOUBLEQUOTE2 : "\""> : PHPPARSING
617 }
618
619 <DOLLAR_IN_STRING> TOKEN :
620 {
621   <LBRACE1 : "{"> : DOLLAR_IN_STRING_EXPR
622 }
623
624 <IN_STRING> SPECIAL_TOKEN :
625 {
626     <"{"> : SKIPSTRING
627 }
628
629 <SKIPSTRING> SPECIAL_TOKEN :
630 {
631     <"}"> : IN_STRING
632 }
633
634 <SKIPSTRING> SKIP :
635 {
636     <~[]>
637 }
638
639 <DOLLAR_IN_STRING_EXPR> TOKEN :
640 {
641   <RBRACE1 : "}"> : DOLLAR_IN_STRING
642 }
643
644 <DOLLAR_IN_STRING_EXPR> TOKEN :
645 {
646   <ID : (~["}"])*>
647 }
648
649 <IN_STRING> SKIP :
650 {
651   <~[]>
652 }
653
654 <DOLLAR_IN_STRING_EXPR,IN_STRING> SKIP :
655 {
656   <~[]>
657 }
658 /* IDENTIFIERS */
659
660
661 <PHPPARSING,IN_VARIABLE> TOKEN : {<DOLLAR : "$"> : IN_VARIABLE}
662
663
664 <PHPPARSING, IN_VARIABLE, DOLLAR_IN_STRING> TOKEN :
665 {
666   <IDENTIFIER: (<LETTER>|<SPECIAL>) (<LETTER>|<DIGIT>|<SPECIAL>)* >
667 |
668   < #LETTER:
669       ["a"-"z"] | ["A"-"Z"]
670   >
671 |
672   < #DIGIT:
673       ["0"-"9"]
674   >
675 |
676   < #SPECIAL:
677     "_" | ["\u007f"-"\u00ff"]
678   >
679 }
680
681 <DOLLAR_IN_STRING> SPECIAL_TOKEN :
682 {
683  < ~[] > : IN_STRING
684 }
685 /* SEPARATORS */
686
687 <PHPPARSING,IN_VARIABLE> TOKEN :
688 {
689   <LPAREN    : "("> : PHPPARSING
690 | <RPAREN    : ")"> : PHPPARSING
691 | <LBRACE    : "{"> : PHPPARSING
692 | <RBRACE    : "}"> : PHPPARSING
693 | <LBRACKET  : "["> : PHPPARSING
694 | <RBRACKET  : "]"> : PHPPARSING
695 | <SEMICOLON : ";"> : PHPPARSING
696 | <COMMA     : ","> : PHPPARSING
697 | <DOT       : "."> : PHPPARSING
698 }
699
700
701 /* COMPARATOR */
702 <PHPPARSING,IN_VARIABLE> TOKEN :
703 {
704   <GT                 : ">"> : PHPPARSING
705 | <LT                 : "<"> : PHPPARSING
706 | <EQUAL_EQUAL        : "=="> : PHPPARSING
707 | <LE                 : "<="> : PHPPARSING
708 | <GE                 : ">="> : PHPPARSING
709 | <NOT_EQUAL          : "!="> : PHPPARSING
710 | <DIF                : "<>"> : PHPPARSING
711 | <BANGDOUBLEEQUAL    : "!=="> : PHPPARSING
712 | <TRIPLEEQUAL        : "==="> : PHPPARSING
713 }
714
715 /* ASSIGNATION */
716 <PHPPARSING,IN_VARIABLE> TOKEN :
717 {
718   <ASSIGN             : "="> : PHPPARSING
719 | <PLUSASSIGN         : "+="> : PHPPARSING
720 | <MINUSASSIGN        : "-="> : PHPPARSING
721 | <STARASSIGN         : "*="> : PHPPARSING
722 | <SLASHASSIGN        : "/="> : PHPPARSING
723 | <ANDASSIGN          : "&="> : PHPPARSING
724 | <ORASSIGN           : "|="> : PHPPARSING
725 | <XORASSIGN          : "^="> : PHPPARSING
726 | <DOTASSIGN          : ".="> : PHPPARSING
727 | <REMASSIGN          : "%="> : PHPPARSING
728 | <TILDEEQUAL         : "~="> : PHPPARSING
729 | <LSHIFTASSIGN       : "<<="> : PHPPARSING
730 | <RSIGNEDSHIFTASSIGN : ">>="> : PHPPARSING
731 }
732
733 void phpTest() :
734 {}
735 {
736   Php()
737   <EOF>
738 }
739
740 void phpFile() :
741 {}
742 {
743   try {
744     (PhpBlock())*
745     {PHPParser.createNewHTMLCode();}
746   } catch (TokenMgrError e) {
747     PHPeclipsePlugin.log(e);
748     errorStart   = SimpleCharStream.beginOffset;
749     errorEnd     = SimpleCharStream.endOffset;
750     errorMessage = e.getMessage();
751     errorLevel   = ERROR;
752     throw generateParseException();
753   }
754 }
755
756 /**
757  * A php block is a <?= expression [;]?>
758  * or <?php somephpcode ?>
759  * or <? somephpcode ?>
760  */
761 void PhpBlock() :
762 {
763   final PHPEchoBlock phpEchoBlock;
764   final Token token,phpEnd;
765 }
766 {
767   phpEchoBlock = phpEchoBlock()
768   {pushOnAstNodes(phpEchoBlock);}
769 |
770   [   <PHPSTARTLONG>
771     | token = <PHPSTARTSHORT>
772     {try {
773       setMarker(fileToParse,
774                 "You should use '<?php' instead of '<?' it will avoid some problems with XML",
775                 token.sourceStart,
776                 token.sourceEnd,
777                 INFO,
778                 "Line " + token.beginLine);
779     } catch (CoreException e) {
780       PHPeclipsePlugin.log(e);
781     }}
782   ]
783   {PHPParser.createNewHTMLCode();}
784   Php()
785   try {
786     phpEnd = <PHPEND>
787    {htmlStart = phpEnd.sourceEnd;}
788   } catch (ParseException e) {
789     errorMessage = "'?>' expected";
790     errorLevel   = ERROR;
791     errorStart = SimpleCharStream.getPosition() - e.currentToken.next.image.length() + 1;
792     errorEnd   = SimpleCharStream.getPosition() + 1;
793     processParseExceptionDebug(e);
794   }
795 }
796
797 PHPEchoBlock phpEchoBlock() :
798 {
799   final Expression expr;
800   final PHPEchoBlock echoBlock;
801   final Token token, token2;
802 }
803 {
804   token = <PHPECHOSTART> {PHPParser.createNewHTMLCode();}
805   expr = Expression() [ <SEMICOLON> ] token2 = <PHPEND>
806   {
807   htmlStart = token2.sourceEnd;
808
809   echoBlock = new PHPEchoBlock(expr,token.sourceStart,token2.sourceEnd);
810   pushOnAstNodes(echoBlock);
811   return echoBlock;}
812 }
813
814 void Php() :
815 {}
816 {
817   (BlockStatement())*
818 }
819
820 ClassDeclaration ClassDeclaration() :
821 {
822   final ClassDeclaration classDeclaration;
823   Token className = null;
824   final Token superclassName, token, extendsToken;
825   String classNameImage = SYNTAX_ERROR_CHAR;
826   String superclassNameImage = null;
827   final int classEnd;
828 }
829 {
830   token = <CLASS>
831   try {
832     className = <IDENTIFIER>
833     {classNameImage = className.image;}
834   } catch (ParseException e) {
835     errorMessage = "unexpected token : '"+ e.currentToken.next.image +"', identifier expected";
836     errorLevel   = ERROR;
837     errorStart   = token.sourceEnd+1;
838     errorEnd     = token.sourceEnd+1;
839     processParseExceptionDebug(e);
840   }
841   [
842     extendsToken = <EXTENDS>
843     try {
844       superclassName = <IDENTIFIER>
845       {superclassNameImage = superclassName.image;}
846     } catch (ParseException e) {
847       errorMessage = "unexpected token : '"+ e.currentToken.next.image +"', identifier expected";
848       errorLevel   = ERROR;
849       errorStart = extendsToken.sourceEnd+1;
850       errorEnd   = extendsToken.sourceEnd+1;
851       processParseExceptionDebug(e);
852       superclassNameImage = SYNTAX_ERROR_CHAR;
853     }
854   ]
855   {
856     int start, end;
857     if (className == null) {
858       start = token.sourceStart;
859       end = token.sourceEnd;
860     } else {
861       start = className.sourceStart;
862       end = className.sourceEnd;
863     }
864     if (superclassNameImage == null) {
865
866       classDeclaration = new ClassDeclaration(currentSegment,
867                                               classNameImage,
868                                               start,
869                                               end);
870     } else {
871       classDeclaration = new ClassDeclaration(currentSegment,
872                                               classNameImage,
873                                               superclassNameImage,
874                                               start,
875                                               end);
876     }
877       currentSegment.add(classDeclaration);
878       currentSegment = classDeclaration;
879   }
880   classEnd = ClassBody(classDeclaration)
881   {currentSegment = (OutlineableWithChildren) currentSegment.getParent();
882    classDeclaration.sourceEnd = classEnd;
883    pushOnAstNodes(classDeclaration);
884    return classDeclaration;}
885 }
886
887 int ClassBody(final ClassDeclaration classDeclaration) :
888 {
889 Token token;
890 }
891 {
892   try {
893     <LBRACE>
894   } catch (ParseException e) {
895     errorMessage = "unexpected token : '"+ e.currentToken.next.image + "'. '{' expected";
896     errorLevel   = ERROR;
897     errorStart = SimpleCharStream.getPosition() - e.currentToken.next.image.length() + 1;
898     errorEnd   = SimpleCharStream.getPosition() + 1;
899     processParseExceptionDebug(e);
900   }
901   ( ClassBodyDeclaration(classDeclaration) )*
902   try {
903     token = <RBRACE>
904     {return token.sourceEnd;}
905   } catch (ParseException e) {
906     errorMessage = "unexpected token : '"+ e.currentToken.next.image +"'. 'var', 'function' or '}' expected";
907     errorLevel   = ERROR;
908     errorStart = SimpleCharStream.getPosition() - e.currentToken.next.image.length() + 1;
909     errorEnd   = SimpleCharStream.getPosition() + 1;
910     processParseExceptionDebug(e);
911     return PHPParser.token.sourceEnd;
912   }
913 }
914
915 /**
916  * A class can contain only methods and fields.
917  */
918 void ClassBodyDeclaration(final ClassDeclaration classDeclaration) :
919 {
920   final MethodDeclaration method;
921   final FieldDeclaration field;
922 }
923 {
924   method = MethodDeclaration() {method.analyzeCode();
925                                 classDeclaration.addMethod(method);}
926 | field = FieldDeclaration()   {classDeclaration.addField(field);}
927 }
928
929 /**
930  * A class field declaration : it's var VariableDeclarator() (, VariableDeclarator())*;.
931  * it is only used by ClassBodyDeclaration()
932  */
933 FieldDeclaration FieldDeclaration() :
934 {
935   VariableDeclaration variableDeclaration;
936   final VariableDeclaration[] list;
937   final ArrayList arrayList = new ArrayList();
938   final Token token;
939   Token token2 = null;
940   int pos;
941 }
942 {
943   token = <VAR> variableDeclaration = VariableDeclaratorNoSuffix()
944   {
945     arrayList.add(variableDeclaration);
946     outlineInfo.addVariable(variableDeclaration.name());
947     pos = variableDeclaration.sourceEnd;
948   }
949   (
950     <COMMA> variableDeclaration = VariableDeclaratorNoSuffix()
951       {
952         arrayList.add(variableDeclaration);
953         outlineInfo.addVariable(variableDeclaration.name());
954         pos = variableDeclaration.sourceEnd;
955       }
956   )*
957   try {
958     token2 = <SEMICOLON>
959   } catch (ParseException e) {
960     errorMessage = "unexpected token : '"+ e.currentToken.next.image +"'. A ';' was expected after variable declaration";
961     errorLevel   = ERROR;
962     errorStart   = pos+1;
963     errorEnd     = pos+1;
964     processParseExceptionDebug(e);
965   }
966
967   {list = new VariableDeclaration[arrayList.size()];
968    arrayList.toArray(list);
969    int end;
970    if (token2 == null) {
971      end = list[list.length-1].sourceEnd;
972    } else {
973      end = token2.sourceEnd;
974    }
975    return new FieldDeclaration(list,
976                                token.sourceStart,
977                                end,
978                                currentSegment);}
979 }
980
981 /**
982  * a strict variable declarator : there cannot be a suffix here.
983  * It will be used by fields and formal parameters
984  */
985 VariableDeclaration VariableDeclaratorNoSuffix() :
986 {
987   final Token token, lbrace,rbrace;
988   Expression expr, initializer = null;
989   Token assignToken;
990   Variable variable;
991 }
992 {
993   <DOLLAR>
994   (
995      token = <IDENTIFIER>
996      {variable = new Variable(token.image,token.sourceStart,token.sourceEnd);}
997    |
998      lbrace = <LBRACE> expr = Expression() rbrace = <RBRACE>
999      {variable = new Variable(expr,lbrace.sourceStart,rbrace.sourceEnd);}
1000   )
1001   [
1002     assignToken = <ASSIGN>
1003     try {
1004       initializer = VariableInitializer()
1005     } catch (ParseException e) {
1006       errorMessage = "Literal expression expected in variable initializer";
1007       errorLevel   = ERROR;
1008       errorStart = assignToken.sourceEnd +1;
1009       errorEnd   = assignToken.sourceEnd +1;
1010       processParseExceptionDebug(e);
1011     }
1012   ]
1013   {
1014   if (initializer == null) {
1015     return new VariableDeclaration(currentSegment,
1016                                    variable,
1017                                    variable.sourceStart,
1018                                    variable.sourceEnd);
1019   }
1020   return new VariableDeclaration(currentSegment,
1021                                  variable,
1022                                  initializer,
1023                                  VariableDeclaration.EQUAL,
1024                                  variable.sourceStart);
1025   }
1026 }
1027
1028 /**
1029  * this will be used by static statement
1030  */
1031 VariableDeclaration VariableDeclarator() :
1032 {
1033   final AbstractVariable variable;
1034   Expression initializer = null;
1035   final Token token;
1036 }
1037 {
1038   variable = VariableDeclaratorId()
1039   [
1040     token = <ASSIGN>
1041     try {
1042       initializer = VariableInitializer()
1043     } catch (ParseException e) {
1044       errorMessage = "Literal expression expected in variable initializer";
1045       errorLevel   = ERROR;
1046       errorStart = token.sourceEnd+1;
1047       errorEnd   = token.sourceEnd+1;
1048       processParseExceptionDebug(e);
1049     }
1050   ]
1051   {
1052   if (initializer == null) {
1053     return new VariableDeclaration(currentSegment,
1054                                    variable,
1055                                    variable.sourceStart,
1056                                    variable.sourceEnd);
1057   }
1058     return new VariableDeclaration(currentSegment,
1059                                    variable,
1060                                    initializer,
1061                                    VariableDeclaration.EQUAL,
1062                                    variable.sourceStart);
1063   }
1064 }
1065
1066 /**
1067  * A Variable name.
1068  * @return the variable name (with suffix)
1069  */
1070 AbstractVariable VariableDeclaratorId() :
1071 {
1072   final Variable var;
1073   AbstractVariable expression = null;
1074 }
1075 {
1076   try {
1077     var = Variable()
1078     (
1079       LOOKAHEAD(2)
1080       expression = VariableSuffix(var)
1081     )*
1082     {
1083      if (expression == null) {
1084        return var;
1085      }
1086      return expression;
1087     }
1088   } catch (ParseException e) {
1089     errorMessage = "'$' expected for variable identifier";
1090     errorLevel   = ERROR;
1091     errorStart = SimpleCharStream.getPosition() - e.currentToken.next.image.length() + 1;
1092     errorEnd   = SimpleCharStream.getPosition() + 1;
1093     throw e;
1094   }
1095 }
1096
1097 Variable Variable() :
1098 {
1099   Variable variable = null;
1100   final Token token;
1101 }
1102 {
1103   token = <DOLLAR> variable = Var()
1104   {
1105     return variable;
1106   }
1107 }
1108
1109 Variable Var() :
1110 {
1111   Variable variable = null;
1112   final Token token,token2;
1113   ConstantIdentifier constant;
1114   Expression expression;
1115 }
1116 {
1117   token = <DOLLAR> variable = Var()
1118   {return new Variable(variable,variable.sourceStart,variable.sourceEnd);}
1119 |
1120   token = <LBRACE> expression = Expression() token2 = <RBRACE>
1121   {
1122    return new Variable(expression,
1123                        token.sourceStart,
1124                        token2.sourceEnd);
1125   }
1126 |
1127   token = <IDENTIFIER>
1128   {return new Variable(token.image,token.sourceStart,token.sourceEnd);}
1129 }
1130
1131 Expression VariableInitializer() :
1132 {
1133   final Expression expr;
1134   final Token token, token2;
1135 }
1136 {
1137   expr = Literal()
1138   {return expr;}
1139 |
1140   token2 = <MINUS> (token = <INTEGER_LITERAL> | token = <FLOATING_POINT_LITERAL>)
1141   {return new PrefixedUnaryExpression(new NumberLiteral(token),
1142                                       OperatorIds.MINUS,
1143                                       token2.sourceStart);}
1144 |
1145   token2 = <PLUS> (token = <INTEGER_LITERAL> | token = <FLOATING_POINT_LITERAL>)
1146   {return new PrefixedUnaryExpression(new NumberLiteral(token),
1147                                       OperatorIds.PLUS,
1148                                       token2.sourceStart);}
1149 |
1150   expr = ArrayDeclarator()
1151   {return expr;}
1152 |
1153   token = <IDENTIFIER>
1154   {return new ConstantIdentifier(token);}
1155 }
1156
1157 ArrayVariableDeclaration ArrayVariable() :
1158 {
1159 final Expression expr,expr2;
1160 }
1161 {
1162   expr = Expression()
1163   [
1164     <ARRAYASSIGN> expr2 = Expression()
1165     {return new ArrayVariableDeclaration(expr,expr2);}
1166   ]
1167   {return new ArrayVariableDeclaration(expr,SimpleCharStream.getPosition());}
1168 }
1169
1170 ArrayVariableDeclaration[] ArrayInitializer() :
1171 {
1172   ArrayVariableDeclaration expr;
1173   final ArrayList list = new ArrayList();
1174 }
1175 {
1176   <LPAREN>
1177     [
1178       expr = ArrayVariable()
1179       {list.add(expr);}
1180       ( LOOKAHEAD(2) <COMMA> expr = ArrayVariable()
1181       {list.add(expr);}
1182       )*
1183     ]
1184     [
1185       <COMMA> {list.add(null);}
1186     ]
1187   <RPAREN>
1188   {
1189   final ArrayVariableDeclaration[] vars = new ArrayVariableDeclaration[list.size()];
1190   list.toArray(vars);
1191   return vars;}
1192 }
1193
1194 /**
1195  * A Method Declaration.
1196  * <b>function</b> MetodDeclarator() Block()
1197  */
1198 MethodDeclaration MethodDeclaration() :
1199 {
1200   final MethodDeclaration functionDeclaration;
1201   final Block block;
1202   final OutlineableWithChildren seg = currentSegment;
1203   final Token token;
1204 }
1205 {
1206   token = <FUNCTION>
1207   try {
1208     functionDeclaration = MethodDeclarator(token.sourceStart)
1209     {outlineInfo.addVariable(functionDeclaration.name);}
1210   } catch (ParseException e) {
1211     if (errorMessage != null)  throw e;
1212     errorMessage = "unexpected token : '"+ e.currentToken.next.image +"', function identifier expected";
1213     errorLevel   = ERROR;
1214     errorStart = SimpleCharStream.getPosition() - e.currentToken.next.image.length() + 1;
1215     errorEnd   = SimpleCharStream.getPosition() + 1;
1216     throw e;
1217   }
1218   {currentSegment = functionDeclaration;}
1219   block = Block()
1220   {functionDeclaration.statements = block.statements;
1221    currentSegment = seg;
1222    return functionDeclaration;}
1223 }
1224
1225 /**
1226  * A MethodDeclarator.
1227  * [&] IDENTIFIER(parameters ...).
1228  * @return a function description for the outline
1229  */
1230 MethodDeclaration MethodDeclarator(final int start) :
1231 {
1232   Token identifier = null;
1233   Token reference = null;
1234   final Hashtable formalParameters = new Hashtable();
1235   String identifierChar = SYNTAX_ERROR_CHAR;
1236   int end = start;
1237 }
1238 {
1239   [reference = <BIT_AND> {end = reference.sourceEnd;}]
1240   try {
1241     identifier = <IDENTIFIER>
1242     {
1243       identifierChar = identifier.image;
1244       end = identifier.sourceEnd;
1245     }
1246   } catch (ParseException e) {
1247     errorMessage = "unexpected token : '"+ e.currentToken.next.image +"', function identifier expected";
1248     errorLevel   = ERROR;
1249     errorStart = e.currentToken.sourceEnd;
1250     errorEnd   = e.currentToken.next.sourceStart;
1251     processParseExceptionDebug(e);
1252   }
1253   end = FormalParameters(formalParameters)
1254   {
1255   int nameStart, nameEnd;
1256   if (identifier == null) {
1257     if (reference == null) {
1258       nameStart = start + 9;
1259       nameEnd = start + 10;
1260     } else {
1261       nameStart = reference.sourceEnd + 1;
1262       nameEnd = reference.sourceEnd + 2;
1263     }
1264   } else {
1265       nameStart = identifier.sourceStart;
1266       nameEnd = identifier.sourceEnd;
1267   }
1268   return new MethodDeclaration(currentSegment,
1269                                identifierChar,
1270                                formalParameters,
1271                                reference != null,
1272                                nameStart,
1273                                nameEnd,
1274                                start,
1275                                end);
1276   }
1277 }
1278
1279 /**
1280  * FormalParameters follows method identifier.
1281  * (FormalParameter())
1282  */
1283 int FormalParameters(final Hashtable parameters) :
1284 {
1285   VariableDeclaration var;
1286   final Token token;
1287   Token tok = PHPParser.token;
1288   int end = tok.sourceEnd;
1289 }
1290 {
1291   try {
1292   tok = <LPAREN>
1293   {end = tok.sourceEnd;}
1294   } catch (ParseException e) {
1295     errorMessage = "unexpected token : '"+ e.currentToken.next.image +"', '(' expected after function identifier";
1296     errorLevel   = ERROR;
1297     errorStart = e.currentToken.next.sourceStart;
1298     errorEnd   = e.currentToken.next.sourceEnd;
1299     processParseExceptionDebug(e);
1300   }
1301   [
1302     var = FormalParameter()
1303     {parameters.put(var.name(),var);end = var.sourceEnd;}
1304     (
1305       <COMMA> var = FormalParameter()
1306       {parameters.put(var.name(),var);end = var.sourceEnd;}
1307     )*
1308   ]
1309   try {
1310     token = <RPAREN>
1311     {end = token.sourceEnd;}
1312   } catch (ParseException e) {
1313     errorMessage = "')' expected";
1314     errorLevel   = ERROR;
1315     errorStart = e.currentToken.next.sourceStart;
1316     errorEnd   = e.currentToken.next.sourceEnd;
1317     processParseExceptionDebug(e);
1318   }
1319  {return end;}
1320 }
1321
1322 /**
1323  * A formal parameter.
1324  * $varname[=value] (,$varname[=value])
1325  */
1326 VariableDeclaration FormalParameter() :
1327 {
1328   final VariableDeclaration variableDeclaration;
1329   Token token = null;
1330 }
1331 {
1332   [token = <BIT_AND>] variableDeclaration = VariableDeclaratorNoSuffix()
1333   {
1334     if (token != null) {
1335       variableDeclaration.setReference(true);
1336     }
1337     return variableDeclaration;}
1338 }
1339
1340 ConstantIdentifier Type() :
1341 {final Token token;}
1342 {
1343   token = <STRING>    {return new ConstantIdentifier(token);}
1344 | token = <BOOL>      {return new ConstantIdentifier(token);}
1345 | token = <BOOLEAN>   {return new ConstantIdentifier(token);}
1346 | token = <REAL>      {return new ConstantIdentifier(token);}
1347 | token = <DOUBLE>    {return new ConstantIdentifier(token);}
1348 | token = <FLOAT>     {return new ConstantIdentifier(token);}
1349 | token = <INT>       {return new ConstantIdentifier(token);}
1350 | token = <INTEGER>   {return new ConstantIdentifier(token);}
1351 | token = <OBJECT>    {return new ConstantIdentifier(token);}
1352 }
1353
1354 Expression Expression() :
1355 {
1356   final Expression expr;
1357   Expression initializer = null;
1358   int assignOperator = -1;
1359 }
1360 {
1361   LOOKAHEAD(1)
1362   expr = ConditionalExpression()
1363   [
1364     assignOperator = AssignmentOperator()
1365     try {
1366       initializer = Expression()
1367     } catch (ParseException e) {
1368       if (errorMessage != null) {
1369         throw e;
1370       }
1371       errorMessage = "unexpected token : '"+ e.currentToken.next.image +"', expression expected";
1372       errorLevel   = ERROR;
1373       errorEnd   = SimpleCharStream.getPosition();
1374       throw e;
1375     }
1376   ]
1377   {
1378     if (assignOperator != -1) {// todo : change this, very very bad :(
1379         if (expr instanceof AbstractVariable) {
1380           return new VariableDeclaration(currentSegment,
1381                                          (AbstractVariable) expr,
1382                                          initializer,
1383                                          expr.sourceStart,
1384                                          initializer.sourceEnd);
1385         }
1386         String varName = expr.toStringExpression().substring(1);
1387         return new VariableDeclaration(currentSegment,
1388                                        new Variable(varName,
1389                                                     expr.sourceStart,
1390                                                     expr.sourceEnd),
1391                                        expr.sourceStart,
1392                                        initializer.sourceEnd);
1393     }
1394     return expr;
1395   }
1396 | expr = ExpressionWBang()       {return expr;}
1397 }
1398
1399 Expression ExpressionWBang() :
1400 {
1401   final Expression expr;
1402   final Token token;
1403 }
1404 {
1405   token = <BANG> expr = ExpressionWBang()
1406   {return new PrefixedUnaryExpression(expr,OperatorIds.NOT,token.sourceStart);}
1407 | expr = ExpressionNoBang() {return expr;}
1408 }
1409
1410 Expression ExpressionNoBang() :
1411 {
1412   Expression expr;
1413 }
1414 {
1415   expr = ListExpression()    {return expr;}
1416 |
1417   expr = PrintExpression()   {return expr;}
1418 }
1419
1420 /**
1421  * Any assignement operator.
1422  * @return the assignement operator id
1423  */
1424 int AssignmentOperator() :
1425 {}
1426 {
1427   <ASSIGN>             {return VariableDeclaration.EQUAL;}
1428 | <STARASSIGN>         {return VariableDeclaration.STAR_EQUAL;}
1429 | <SLASHASSIGN>        {return VariableDeclaration.SLASH_EQUAL;}
1430 | <REMASSIGN>          {return VariableDeclaration.REM_EQUAL;}
1431 | <PLUSASSIGN>         {return VariableDeclaration.PLUS_EQUAL;}
1432 | <MINUSASSIGN>        {return VariableDeclaration.MINUS_EQUAL;}
1433 | <LSHIFTASSIGN>       {return VariableDeclaration.LSHIFT_EQUAL;}
1434 | <RSIGNEDSHIFTASSIGN> {return VariableDeclaration.RSIGNEDSHIFT_EQUAL;}
1435 | <ANDASSIGN>          {return VariableDeclaration.AND_EQUAL;}
1436 | <XORASSIGN>          {return VariableDeclaration.XOR_EQUAL;}
1437 | <ORASSIGN>           {return VariableDeclaration.OR_EQUAL;}
1438 | <DOTASSIGN>          {return VariableDeclaration.DOT_EQUAL;}
1439 | <TILDEEQUAL>         {return VariableDeclaration.TILDE_EQUAL;}
1440 }
1441
1442 Expression ConditionalExpression() :
1443 {
1444   final Expression expr;
1445   Expression expr2 = null;
1446   Expression expr3 = null;
1447 }
1448 {
1449   expr = ConditionalOrExpression() [ <HOOK> expr2 = Expression() <COLON> expr3 = ConditionalExpression() ]
1450 {
1451   if (expr3 == null) {
1452     return expr;
1453   }
1454   return new ConditionalExpression(expr,expr2,expr3);
1455 }
1456 }
1457
1458 Expression ConditionalOrExpression() :
1459 {
1460   Expression expr,expr2;
1461   int operator;
1462 }
1463 {
1464   expr = ConditionalAndExpression()
1465   (
1466     (
1467         <OR_OR> {operator = OperatorIds.OR_OR;}
1468       | <_ORL>  {operator = OperatorIds.ORL;}
1469     )
1470     expr2 = ConditionalAndExpression()
1471     {
1472       expr = new BinaryExpression(expr,expr2,operator);
1473     }
1474   )*
1475   {return expr;}
1476 }
1477
1478 Expression ConditionalAndExpression() :
1479 {
1480   Expression expr,expr2;
1481   int operator;
1482 }
1483 {
1484   expr = ConcatExpression()
1485   (
1486   (  <AND_AND> {operator = OperatorIds.AND_AND;}
1487    | <_ANDL>   {operator = OperatorIds.ANDL;})
1488    expr2 = ConcatExpression() {expr = new BinaryExpression(expr,expr2,operator);}
1489   )*
1490   {return expr;}
1491 }
1492
1493 Expression ConcatExpression() :
1494 {
1495   Expression expr,expr2;
1496 }
1497 {
1498   expr = InclusiveOrExpression()
1499   (
1500     <DOT> expr2 = InclusiveOrExpression()
1501     {expr = new BinaryExpression(expr,expr2,OperatorIds.DOT);}
1502   )*
1503   {return expr;}
1504 }
1505
1506 Expression InclusiveOrExpression() :
1507 {
1508   Expression expr,expr2;
1509 }
1510 {
1511   expr = ExclusiveOrExpression()
1512   (<BIT_OR> expr2 = ExclusiveOrExpression()
1513    {expr = new BinaryExpression(expr,expr2,OperatorIds.OR);}
1514   )*
1515   {return expr;}
1516 }
1517
1518 Expression ExclusiveOrExpression() :
1519 {
1520   Expression expr,expr2;
1521 }
1522 {
1523   expr = AndExpression()
1524   (
1525     <XOR> expr2 = AndExpression()
1526     {expr = new BinaryExpression(expr,expr2,OperatorIds.XOR);}
1527   )*
1528   {return expr;}
1529 }
1530
1531 Expression AndExpression() :
1532 {
1533   Expression expr,expr2;
1534 }
1535 {
1536   expr = EqualityExpression()
1537   (
1538     LOOKAHEAD(1)
1539     <BIT_AND> expr2 = EqualityExpression()
1540     {expr = new BinaryExpression(expr,expr2,OperatorIds.AND);}
1541   )*
1542   {return expr;}
1543 }
1544
1545 Expression EqualityExpression() :
1546 {
1547   Expression expr,expr2;
1548   int operator;
1549   Token token;
1550 }
1551 {
1552   expr = RelationalExpression()
1553   (
1554   (   token = <EQUAL_EQUAL>      {operator = OperatorIds.EQUAL_EQUAL;}
1555     | token = <DIF>              {operator = OperatorIds.DIF;}
1556     | token = <NOT_EQUAL>        {operator = OperatorIds.DIF;}
1557     | token = <BANGDOUBLEEQUAL>  {operator = OperatorIds.BANG_EQUAL_EQUAL;}
1558     | token = <TRIPLEEQUAL>      {operator = OperatorIds.EQUAL_EQUAL_EQUAL;}
1559   )
1560   try {
1561     expr2 = RelationalExpression()
1562   } catch (ParseException e) {
1563     if (errorMessage != null) {
1564       throw e;
1565     }
1566     errorMessage = "unexpected token : '"+ e.currentToken.next.image +"', expression expected";
1567     errorLevel   = ERROR;
1568     errorStart = token.sourceEnd +1;
1569     errorEnd   = token.sourceEnd +1;
1570     expr2 = new ConstantIdentifier(SYNTAX_ERROR_CHAR,token.sourceEnd +1,token.sourceEnd +1);
1571     processParseExceptionDebug(e);
1572   }
1573   {
1574     expr = new BinaryExpression(expr,expr2,operator);
1575   }
1576   )*
1577   {return expr;}
1578 }
1579
1580 Expression RelationalExpression() :
1581 {
1582   Expression expr,expr2;
1583   int operator;
1584 }
1585 {
1586   expr = ShiftExpression()
1587   (
1588   ( <LT> {operator = OperatorIds.LESS;}
1589   | <GT> {operator = OperatorIds.GREATER;}
1590   | <LE> {operator = OperatorIds.LESS_EQUAL;}
1591   | <GE> {operator = OperatorIds.GREATER_EQUAL;})
1592    expr2 = ShiftExpression()
1593   {expr = new BinaryExpression(expr,expr2,operator);}
1594   )*
1595   {return expr;}
1596 }
1597
1598 Expression ShiftExpression() :
1599 {
1600   Expression expr,expr2;
1601   int operator;
1602 }
1603 {
1604   expr = AdditiveExpression()
1605   (
1606   ( <LSHIFT>         {operator = OperatorIds.LEFT_SHIFT;}
1607   | <RSIGNEDSHIFT>   {operator = OperatorIds.RIGHT_SHIFT;}
1608   | <RUNSIGNEDSHIFT> {operator = OperatorIds.UNSIGNED_RIGHT_SHIFT;})
1609   expr2 = AdditiveExpression()
1610   {expr = new BinaryExpression(expr,expr2,operator);}
1611   )*
1612   {return expr;}
1613 }
1614
1615 Expression AdditiveExpression() :
1616 {
1617   Expression expr,expr2;
1618   int operator;
1619 }
1620 {
1621   expr = MultiplicativeExpression()
1622   (
1623     LOOKAHEAD(1)
1624      ( <PLUS>  {operator = OperatorIds.PLUS;}
1625      | <MINUS> {operator = OperatorIds.MINUS;}
1626   )
1627    expr2 = MultiplicativeExpression()
1628   {expr = new BinaryExpression(expr,expr2,operator);}
1629    )*
1630   {return expr;}
1631 }
1632
1633 Expression MultiplicativeExpression() :
1634 {
1635   Expression expr,expr2;
1636   int operator;
1637 }
1638 {
1639   try {
1640     expr = UnaryExpression()
1641   } catch (ParseException e) {
1642     if (errorMessage != null) throw e;
1643     errorMessage = "unexpected token '"+e.currentToken.next.image+"'";
1644     errorLevel   = ERROR;
1645     errorStart = PHPParser.token.sourceStart;
1646     errorEnd   = PHPParser.token.sourceEnd;
1647     throw e;
1648   }
1649   (
1650    (  <STAR>      {operator = OperatorIds.MULTIPLY;}
1651     | <SLASH>     {operator = OperatorIds.DIVIDE;}
1652     | <REMAINDER> {operator = OperatorIds.REMAINDER;})
1653     expr2 = UnaryExpression()
1654     {expr = new BinaryExpression(expr,expr2,operator);}
1655   )*
1656   {return expr;}
1657 }
1658
1659 /**
1660  * An unary expression starting with @, & or nothing
1661  */
1662 Expression UnaryExpression() :
1663 {
1664   final Expression expr;
1665 }
1666 {
1667  /* <BIT_AND> expr = UnaryExpressionNoPrefix()             //why did I had that ?
1668   {return new PrefixedUnaryExpression(expr,OperatorIds.AND,pos);}
1669 |      */
1670   expr = AtNotTildeUnaryExpression() {return expr;}
1671 }
1672
1673 Expression AtNotTildeUnaryExpression() :
1674 {
1675   final Expression expr;
1676   final Token token;
1677 }
1678 {
1679   token = <AT>
1680   expr = AtNotTildeUnaryExpression()
1681   {return new PrefixedUnaryExpression(expr,OperatorIds.AT,token.sourceStart);}
1682 |
1683   token = <TILDE>
1684   expr = AtNotTildeUnaryExpression()
1685   {return new PrefixedUnaryExpression(expr,OperatorIds.TWIDDLE,token.sourceStart);}
1686 |
1687   token = <BANG>
1688   expr = AtNotUnaryExpression()
1689   {return new PrefixedUnaryExpression(expr,OperatorIds.NOT,token.sourceStart);}
1690 |
1691   expr = UnaryExpressionNoPrefix()
1692   {return expr;}
1693 }
1694
1695 /**
1696  * An expression prefixed (or not) by one or more @ and !.
1697  * @return the expression
1698  */
1699 Expression AtNotUnaryExpression() :
1700 {
1701   final Expression expr;
1702   final Token token;
1703 }
1704 {
1705   token = <AT>
1706   expr = AtNotUnaryExpression()
1707   {return new PrefixedUnaryExpression(expr,OperatorIds.AT,token.sourceStart);}
1708 |
1709   token = <BANG>
1710   expr = AtNotUnaryExpression()
1711   {return new PrefixedUnaryExpression(expr,OperatorIds.NOT,token.sourceStart);}
1712 |
1713   expr = UnaryExpressionNoPrefix()
1714   {return expr;}
1715 }
1716
1717 Expression UnaryExpressionNoPrefix() :
1718 {
1719   final Expression expr;
1720   final Token token;
1721 }
1722 {
1723   token = <PLUS> expr = AtNotTildeUnaryExpression()   {return new PrefixedUnaryExpression(expr,
1724                                                                                      OperatorIds.PLUS,
1725                                                                                      token.sourceStart);}
1726 |
1727   token = <MINUS> expr = AtNotTildeUnaryExpression()  {return new PrefixedUnaryExpression(expr,
1728                                                                                      OperatorIds.MINUS,
1729                                                                                      token.sourceStart);}
1730 |
1731   expr = PreIncDecExpression()
1732   {return expr;}
1733 |
1734   expr = UnaryExpressionNotPlusMinus()
1735   {return expr;}
1736 }
1737
1738
1739 Expression PreIncDecExpression() :
1740 {
1741 final Expression expr;
1742 final int operator;
1743 final Token token;
1744 }
1745 {
1746   (
1747       token = <PLUS_PLUS>   {operator = OperatorIds.PLUS_PLUS;}
1748     |
1749       token = <MINUS_MINUS> {operator = OperatorIds.MINUS_MINUS;}
1750   )
1751   expr = PrimaryExpression()
1752   {return new PrefixedUnaryExpression(expr,operator,token.sourceStart);}
1753 }
1754
1755 Expression UnaryExpressionNotPlusMinus() :
1756 {
1757   final Expression expr;
1758 }
1759 {
1760   LOOKAHEAD( <LPAREN> (Type() | <ARRAY>) <RPAREN> )
1761   expr = CastExpression()         {return expr;}
1762 | expr = PostfixExpression()      {return expr;}
1763 | expr = Literal()                {return expr;}
1764 | <LPAREN> expr = Expression()
1765   try {
1766     <RPAREN>
1767   } catch (ParseException e) {
1768     errorMessage = "')' expected";
1769     errorLevel   = ERROR;
1770     errorStart   = expr.sourceEnd +1;
1771     errorEnd     = expr.sourceEnd +1;
1772     processParseExceptionDebug(e);
1773   }
1774   {return expr;}
1775 }
1776
1777 CastExpression CastExpression() :
1778 {
1779 final ConstantIdentifier type;
1780 final Expression expr;
1781 final Token token,token1;
1782 }
1783 {
1784   token1 = <LPAREN>
1785   (
1786       type = Type()
1787     |
1788       token = <ARRAY> {type = new ConstantIdentifier(token);}
1789   )
1790   <RPAREN> expr = UnaryExpression()
1791   {return new CastExpression(type,expr,token1.sourceStart,expr.sourceEnd);}
1792 }
1793
1794 Expression PostfixExpression() :
1795 {
1796   final Expression expr;
1797   int operator = -1;
1798   Token token = null;
1799 }
1800 {
1801   expr = PrimaryExpression()
1802   [
1803       token = <PLUS_PLUS>   {operator = OperatorIds.PLUS_PLUS;}
1804     |
1805       token = <MINUS_MINUS> {operator = OperatorIds.MINUS_MINUS;}
1806   ]
1807   {
1808     if (operator == -1) {
1809       return expr;
1810     }
1811     return new PostfixedUnaryExpression(expr,operator,token.sourceEnd);
1812   }
1813 }
1814
1815 Expression PrimaryExpression() :
1816 {
1817   Expression expr;
1818   Token token = null;
1819 }
1820 {
1821   [token = <BIT_AND>] expr = refPrimaryExpression(token)
1822   {return expr;}
1823 |
1824   expr = ArrayDeclarator()
1825   {return expr;}
1826 }
1827
1828 Expression refPrimaryExpression(final Token reference) :
1829 {
1830   Expression expr;
1831   Expression expr2 = null;
1832   final Token identifier;
1833 }
1834 {
1835   identifier = <IDENTIFIER>
1836   {
1837     expr = new ConstantIdentifier(identifier);
1838   }
1839   (
1840     <STATICCLASSACCESS> expr2 = ClassIdentifier()
1841     {expr = new ClassAccess(expr,
1842                             expr2,
1843                             ClassAccess.STATIC);}
1844   )*
1845   [ expr2 = Arguments(expr) ]
1846   {
1847     if (expr2 == null) {
1848       if (reference != null) {
1849         ParseException e = generateParseException();
1850         errorMessage = "you cannot use a constant by reference";
1851         errorLevel   = ERROR;
1852         errorStart   = reference.sourceStart;
1853         errorEnd     = reference.sourceEnd;
1854         processParseExceptionDebug(e);
1855       }
1856       return expr;
1857     }
1858     return expr2;
1859   }
1860 |
1861   expr = VariableDeclaratorId()  //todo use the reference parameter ...
1862   [ expr = Arguments(expr) ]
1863   {return expr;}
1864 |
1865   token = <NEW>
1866   expr = ClassIdentifier()
1867   {
1868     int start;
1869     if (reference == null) {
1870       start = token.sourceStart;
1871     } else {
1872       start = reference.sourceStart;
1873     }
1874     expr = new ClassInstantiation(expr,
1875                                   reference != null,
1876                                   start);
1877   }
1878   [ expr = Arguments(expr) ]
1879   {return expr;}
1880 }
1881
1882 /**
1883  * An array declarator.
1884  * array(vars)
1885  * @return an array
1886  */
1887 ArrayInitializer ArrayDeclarator() :
1888 {
1889   final ArrayVariableDeclaration[] vars;
1890   final Token token;
1891 }
1892 {
1893   token = <ARRAY> vars = ArrayInitializer()
1894   {return new ArrayInitializer(vars,
1895                                token.sourceStart,
1896                                PHPParser.token.sourceEnd);}
1897 }
1898
1899 Expression ClassIdentifier():
1900 {
1901   final Expression expr;
1902   final Token token;
1903 }
1904 {
1905   token = <IDENTIFIER>          {return new ConstantIdentifier(token);}
1906 | expr = Type()                 {return expr;}
1907 | expr = VariableDeclaratorId() {return expr;}
1908 }
1909
1910 /**
1911  * Used by Variabledeclaratorid and primarysuffix
1912  */
1913 AbstractVariable VariableSuffix(final AbstractVariable prefix) :
1914 {
1915   Expression expression = null;
1916   final Token classAccessToken,lbrace,rbrace;
1917   Token token;
1918   int pos;
1919 }
1920 {
1921   classAccessToken = <CLASSACCESS>
1922   try {
1923     (
1924       lbrace = <LBRACE> expression = Expression() rbrace = <RBRACE>
1925                 {
1926                  expression = new Variable(expression,
1927                                            lbrace.sourceStart,
1928                                            rbrace.sourceEnd);
1929                 }
1930       |
1931         token = <IDENTIFIER>
1932         {expression = new ConstantIdentifier(token.image,token.sourceStart,token.sourceEnd);}
1933       |
1934         expression = Variable()
1935     )
1936   } catch (ParseException e) {
1937     errorMessage = "unexpected token : '"+ e.currentToken.next.image +"', function call or field access expected";
1938     errorLevel   = ERROR;
1939     errorStart = classAccessToken.sourceEnd +1;
1940     errorEnd   = classAccessToken.sourceEnd +1;
1941     processParseExceptionDebug(e);
1942   }
1943   {return new ClassAccess(prefix,
1944                           expression,
1945                           ClassAccess.NORMAL);}
1946 |
1947   token = <LBRACKET> {pos = token.sourceEnd+1;}
1948   [  expression = Expression() {pos = expression.sourceEnd+1;}
1949    | expression = Type()       {pos = expression.sourceEnd+1;}]  //Not good
1950   try {
1951     token = <RBRACKET>
1952     {pos = token.sourceEnd;}
1953   } catch (ParseException e) {
1954     errorMessage = "']' expected";
1955     errorLevel   = ERROR;
1956     errorStart = pos;
1957     errorEnd   = pos;
1958     processParseExceptionDebug(e);
1959   }
1960   {return new ArrayDeclarator(prefix,expression,pos);}
1961 |
1962   token = <LBRACE> {pos = token.sourceEnd+1;}
1963   [  expression = Expression() {pos = expression.sourceEnd+1;}
1964    | expression = Type()       {pos = expression.sourceEnd+1;}]  //Not good
1965   try {
1966     token = <RBRACE>
1967     {pos = token.sourceEnd;}
1968   } catch (ParseException e) {
1969     errorMessage = "']' expected";
1970     errorLevel   = ERROR;
1971     errorStart = pos;
1972     errorEnd   = pos;
1973     processParseExceptionDebug(e);
1974   }
1975   {return new ArrayDeclarator(prefix,expression,pos);}//todo : check braces here
1976 }
1977
1978 Literal Literal() :
1979 {
1980   final Token token;
1981   StringLiteral literal;
1982 }
1983 {
1984   token = <INTEGER_LITERAL>        {return new NumberLiteral(token);}
1985 | token = <FLOATING_POINT_LITERAL> {return new NumberLiteral(token);}
1986 | token = <STRING_LITERAL>         {return new StringLiteral(token);}
1987 | token = <TRUE>                   {return new TrueLiteral(token);}
1988 | token = <FALSE>                  {return new FalseLiteral(token);}
1989 | token = <NULL>                   {return new NullLiteral(token);}
1990 | literal = evaluableString()        {return literal;}
1991 }
1992
1993 StringLiteral evaluableString() :
1994 {
1995   ArrayList list = new ArrayList();
1996   Token start,end;
1997   Token token,lbrace,rbrace;
1998   AbstractVariable var;
1999   Expression expr;
2000 }
2001 {
2002   start = <DOUBLEQUOTE>
2003   (
2004    <DOLLARS>
2005        (
2006         token = <IDENTIFIER> {list.add(new Variable(token.image,
2007                                                     token.sourceStart,
2008                                                     token.sourceEnd));}
2009         |
2010          lbrace = <LBRACE1>
2011          token = <ID>
2012          {list.add(new Variable(token.image,
2013                                 token.sourceStart,
2014                                 token.sourceEnd));}
2015          rbrace = <RBRACE1>
2016        )
2017    )*
2018   end = <DOUBLEQUOTE2>
2019   {
2020   AbstractVariable[] vars = new AbstractVariable[list.size()];
2021   list.toArray(vars);
2022   return new StringLiteral(SimpleCharStream.currentBuffer.substring(start.sourceEnd,end.sourceStart),
2023                            start.sourceStart,
2024                            end.sourceEnd,
2025                            vars);
2026   }
2027 }
2028
2029 FunctionCall Arguments(final Expression func) :
2030 {
2031 Expression[] args = null;
2032 final Token token,lparen;
2033 }
2034 {
2035   lparen = <LPAREN> [ args = ArgumentList() ]
2036   try {
2037     token = <RPAREN>
2038     {return new FunctionCall(func,args,token.sourceEnd);}
2039   } catch (ParseException e) {
2040     errorMessage = "unexpected token : '"+ e.currentToken.next.image +"', ')' expected to close the argument list";
2041     errorLevel   = ERROR;
2042     if (args == null) {
2043         errorStart = lparen.sourceEnd+1;
2044         errorEnd   = lparen.sourceEnd+2;
2045     } else {
2046         errorStart = args[args.length-1].sourceEnd+1;
2047         errorEnd   = args[args.length-1].sourceEnd+2;
2048     }
2049     processParseExceptionDebug(e);
2050   }
2051   {
2052   int sourceEnd = (args == null && args.length != 0) ? lparen.sourceEnd+1 : args[args.length-1].sourceEnd;
2053   return new FunctionCall(func,args,sourceEnd);}
2054 }
2055
2056 /**
2057  * An argument list is a list of arguments separated by comma :
2058  * argumentDeclaration() (, argumentDeclaration)*
2059  * @return an array of arguments
2060  */
2061 Expression[] ArgumentList() :
2062 {
2063 Expression arg;
2064 final ArrayList list = new ArrayList();
2065 int pos;
2066 Token token;
2067 }
2068 {
2069   arg = Expression()
2070   {list.add(arg);pos = arg.sourceEnd;}
2071   ( token = <COMMA> {pos = token.sourceEnd;}
2072       try {
2073         arg = Expression()
2074         {list.add(arg);
2075          pos = arg.sourceEnd;}
2076       } catch (ParseException e) {
2077         errorMessage = "unexpected token : '"+ e.currentToken.next.image +"'. An expression expected after a comma in argument list";
2078         errorLevel   = ERROR;
2079         errorStart   = pos+1;
2080         errorEnd     = pos+1;
2081         processParseException(e);
2082       }
2083    )*
2084    {
2085    final Expression[] arguments = new Expression[list.size()];
2086    list.toArray(arguments);
2087    return arguments;}
2088 }
2089
2090 /**
2091  * A Statement without break.
2092  * @return a statement
2093  */
2094 Statement StatementNoBreak() :
2095 {
2096   final Statement statement;
2097   Token token = null;
2098 }
2099 {
2100   LOOKAHEAD(2)
2101   statement = expressionStatement()     {return statement;}
2102 | LOOKAHEAD(1)
2103   statement = LabeledStatement()        {return statement;}
2104 | statement = Block()                   {return statement;}
2105 | statement = EmptyStatement()          {return statement;}
2106 | statement = SwitchStatement()         {return statement;}
2107 | statement = IfStatement()             {return statement;}
2108 | statement = WhileStatement()          {return statement;}
2109 | statement = DoStatement()             {return statement;}
2110 | statement = ForStatement()            {return statement;}
2111 | statement = ForeachStatement()        {return statement;}
2112 | statement = ContinueStatement()       {return statement;}
2113 | statement = ReturnStatement()         {return statement;}
2114 | statement = EchoStatement()           {return statement;}
2115 | [token=<AT>] statement = IncludeStatement()
2116   {if (token != null) {
2117     ((InclusionStatement)statement).silent = true;
2118     statement.sourceStart = token.sourceStart;
2119   }
2120   return statement;}
2121 | statement = StaticStatement()         {return statement;}
2122 | statement = GlobalStatement()         {return statement;}
2123 | statement = defineStatement()         {currentSegment.add((Outlineable)statement);return statement;}
2124 }
2125
2126 /**
2127  * A statement expression.
2128  * expression ;
2129  * @return an expression
2130  */
2131 Statement expressionStatement() :
2132 {
2133   final Statement statement;
2134   final Token token;
2135 }
2136 {
2137   statement = Expression()
2138   try {
2139     token = <SEMICOLON>
2140     {statement.sourceEnd = token.sourceEnd;}
2141   } catch (ParseException e) {
2142     if (e.currentToken.next.kind != PHPParserConstants.PHPEND) {
2143       errorMessage = "unexpected token : '"+ e.currentToken.next.image +"'. A ';' was expected";
2144       errorLevel   = ERROR;
2145       errorStart = statement.sourceEnd+1;
2146       errorEnd   = statement.sourceEnd+1;
2147       processParseExceptionDebug(e);
2148     }
2149   }
2150   {return statement;}
2151 }
2152
2153 Define defineStatement() :
2154 {
2155   Expression defineName,defineValue;
2156   final Token defineToken;
2157   Token token;
2158   int pos;
2159 }
2160 {
2161   defineToken = <DEFINE> {pos = defineToken.sourceEnd+1;}
2162   try {
2163     token = <LPAREN>
2164     {pos = token.sourceEnd+1;}
2165   } catch (ParseException e) {
2166     errorMessage = "unexpected token : '"+ e.currentToken.next.image +"', '(' expected";
2167     errorLevel   = ERROR;
2168     errorStart   = pos;
2169     errorEnd     = pos;
2170     processParseExceptionDebug(e);
2171   }
2172   try {
2173     defineName = Expression()
2174     {pos = defineName.sourceEnd+1;}
2175   } catch (ParseException e) {
2176     errorMessage = "unexpected token : '"+ e.currentToken.next.image +"', expression expected";
2177     errorLevel   = ERROR;
2178     errorStart   = pos;
2179     errorEnd     = pos;
2180     processParseExceptionDebug(e);
2181     defineName = new StringLiteral(SYNTAX_ERROR_CHAR,pos,pos);
2182   }
2183   try {
2184     token = <COMMA>
2185     {pos = defineName.sourceEnd+1;}
2186   } catch (ParseException e) {
2187     errorMessage = "unexpected token : '"+ e.currentToken.next.image +"', ',' expected";
2188     errorLevel   = ERROR;
2189     errorStart   = pos;
2190     errorEnd     = pos;
2191     processParseExceptionDebug(e);
2192   }
2193   try {
2194     defineValue = Expression()
2195     {pos = defineValue.sourceEnd+1;}
2196   } catch (ParseException e) {
2197     errorMessage = "unexpected token : '"+ e.currentToken.next.image +"', expression expected";
2198     errorLevel   = ERROR;
2199     errorStart   = pos;
2200     errorEnd     = pos;
2201     processParseExceptionDebug(e);
2202     defineValue = new StringLiteral(SYNTAX_ERROR_CHAR,pos,pos);
2203   }
2204   try {
2205     token = <RPAREN>
2206     {pos = token.sourceEnd+1;}
2207   } catch (ParseException e) {
2208     errorMessage = "unexpected token : '"+ e.currentToken.next.image +"', ')' expected";
2209     errorLevel   = ERROR;
2210     errorStart   = pos;
2211     errorEnd     = pos;
2212     processParseExceptionDebug(e);
2213   }
2214   {return new Define(currentSegment,
2215                      defineName,
2216                      defineValue,
2217                      defineToken.sourceStart,
2218                      pos);}
2219 }
2220
2221 /**
2222  * A Normal statement.
2223  */
2224 Statement Statement() :
2225 {
2226   final Statement statement;
2227 }
2228 {
2229   statement = StatementNoBreak() {return statement;}
2230 | statement = BreakStatement()   {return statement;}
2231 }
2232
2233 /**
2234  * An html block inside a php syntax.
2235  */
2236 HTMLBlock htmlBlock() :
2237 {
2238   final int startIndex = nodePtr;
2239   final AstNode[] blockNodes;
2240   final int nbNodes;
2241   final Token phpEnd;
2242 }
2243 {
2244   phpEnd = <PHPEND>
2245   {htmlStart = phpEnd.sourceEnd;}
2246   (phpEchoBlock())*
2247   try {
2248     (<PHPSTARTLONG> | <PHPSTARTSHORT>)
2249     {PHPParser.createNewHTMLCode();}
2250   } catch (ParseException e) {
2251     errorMessage = "unexpected end of file , '<?php' expected";
2252     errorLevel   = ERROR;
2253     errorStart   = SimpleCharStream.getPosition();
2254     errorEnd     = SimpleCharStream.getPosition();
2255     throw e;
2256   }
2257   {
2258   nbNodes    = nodePtr - startIndex;
2259   if (nbNodes == 0) {
2260     return null;
2261   }
2262   blockNodes = new AstNode[nbNodes];
2263   System.arraycopy(nodes,startIndex+1,blockNodes,0,nbNodes);
2264   nodePtr = startIndex;
2265   return new HTMLBlock(blockNodes);}
2266 }
2267
2268 /**
2269  * An include statement. It's "include" an expression;
2270  */
2271 InclusionStatement IncludeStatement() :
2272 {
2273   Expression expr;
2274   final int keyword;
2275   final InclusionStatement inclusionStatement;
2276   final Token token, token2;
2277   int pos;
2278 }
2279 {
2280       (  token = <REQUIRE>      {keyword = InclusionStatement.REQUIRE;pos=token.sourceEnd;}
2281        | token = <REQUIRE_ONCE> {keyword = InclusionStatement.REQUIRE_ONCE;pos=token.sourceEnd;}
2282        | token = <INCLUDE>      {keyword = InclusionStatement.INCLUDE;pos=token.sourceEnd;}
2283        | token = <INCLUDE_ONCE> {keyword = InclusionStatement.INCLUDE_ONCE;pos=token.sourceEnd;})
2284   try {
2285     expr = Expression()
2286     {pos = expr.sourceEnd;}
2287   } catch (ParseException e) {
2288     if (errorMessage != null) {
2289       throw e;
2290     }
2291     errorMessage = "unexpected token '"+ e.currentToken.next.image+"', expression expected";
2292     errorLevel   = ERROR;
2293     errorStart   = e.currentToken.next.sourceStart;
2294     errorEnd     = e.currentToken.next.sourceEnd;
2295     expr = new ConstantIdentifier(SYNTAX_ERROR_CHAR,pos,pos);
2296     processParseExceptionDebug(e);
2297   }
2298   try {
2299     token2 = <SEMICOLON>
2300     {pos=token2.sourceEnd;}
2301   } catch (ParseException e) {
2302     errorMessage = "unexpected token : '"+ e.currentToken.next.image +"'. A ';' was expected";
2303     errorLevel   = ERROR;
2304     errorStart   = e.currentToken.next.sourceStart;
2305     errorEnd     = e.currentToken.next.sourceEnd;
2306     processParseExceptionDebug(e);
2307   }
2308   {
2309    inclusionStatement = new InclusionStatement(currentSegment,
2310                                                keyword,
2311                                                expr,
2312                                                token.sourceStart,
2313                                                pos);
2314    currentSegment.add(inclusionStatement);
2315    return inclusionStatement;
2316   }
2317 }
2318
2319 PrintExpression PrintExpression() :
2320 {
2321   final Expression expr;
2322   final Token printToken;
2323 }
2324 {
2325   token = <PRINT> expr = Expression()
2326   {return new PrintExpression(expr,token.sourceStart,expr.sourceEnd);}
2327 }
2328
2329 ListExpression ListExpression() :
2330 {
2331   Expression expr = null;
2332   final Expression expression;
2333   final ArrayList list = new ArrayList();
2334   int pos;
2335   final Token listToken, rParen;
2336   Token token;
2337 }
2338 {
2339   listToken = <LIST> {pos = listToken.sourceEnd;}
2340   try {
2341     token = <LPAREN> {pos = token.sourceEnd;}
2342   } catch (ParseException e) {
2343     errorMessage = "unexpected token : '"+ e.currentToken.next.image +"', '(' expected";
2344     errorLevel   = ERROR;
2345     errorStart   = listToken.sourceEnd+1;
2346     errorEnd     = listToken.sourceEnd+1;
2347     processParseExceptionDebug(e);
2348   }
2349   [
2350     expr = VariableDeclaratorId()
2351     {list.add(expr);pos = expr.sourceEnd;}
2352   ]
2353   {if (expr == null) list.add(null);}
2354   (
2355     try {
2356       token = <COMMA>
2357       {pos = token.sourceEnd;}
2358     } catch (ParseException e) {
2359       errorMessage = "unexpected token : '"+ e.currentToken.next.image +"', ',' expected";
2360       errorLevel   = ERROR;
2361       errorStart   = pos+1;
2362       errorEnd     = pos+1;
2363       processParseExceptionDebug(e);
2364     }
2365     [expr = VariableDeclaratorId() {list.add(expr);pos = expr.sourceEnd;}]
2366   )*
2367   try {
2368     rParen = <RPAREN>
2369     {pos = rParen.sourceEnd;}
2370   } catch (ParseException e) {
2371     errorMessage = "unexpected token : '"+ e.currentToken.next.image +"', ')' expected";
2372     errorLevel   = ERROR;
2373     errorStart = pos+1;
2374     errorEnd   = pos+1;
2375       processParseExceptionDebug(e);
2376   }
2377   [ <ASSIGN> expression = Expression()
2378     {
2379     final AbstractVariable[] vars = new AbstractVariable[list.size()];
2380     list.toArray(vars);
2381     return new ListExpression(vars,
2382                               expression,
2383                               listToken.sourceStart,
2384                               expression.sourceEnd);}
2385   ]
2386   {
2387     final AbstractVariable[] vars = new AbstractVariable[list.size()];
2388     list.toArray(vars);
2389     return new ListExpression(vars,listToken.sourceStart,pos);}
2390 }
2391
2392 /**
2393  * An echo statement.
2394  * echo anyexpression (, otherexpression)*
2395  */
2396 EchoStatement EchoStatement() :
2397 {
2398   final ArrayList expressions = new ArrayList();
2399   Expression expr;
2400   Token token;
2401   Token token2 = null;
2402 }
2403 {
2404   token = <ECHO> expr = Expression()
2405   {expressions.add(expr);}
2406   (
2407     <COMMA> expr = Expression()
2408     {expressions.add(expr);}
2409   )*
2410   try {
2411     token2 = <SEMICOLON>
2412   } catch (ParseException e) {
2413     if (e.currentToken.next.kind != 4) {
2414       errorMessage = "';' expected after 'echo' statement";
2415       errorLevel   = ERROR;
2416       errorStart   = e.currentToken.sourceEnd;
2417       errorEnd     = e.currentToken.sourceEnd;
2418       processParseExceptionDebug(e);
2419     }
2420   }
2421   {
2422    final Expression[] exprs = new Expression[expressions.size()];
2423    expressions.toArray(exprs);
2424    if (token2 == null) {
2425      return new EchoStatement(exprs,token.sourceStart, exprs[exprs.length-1].sourceEnd);
2426    }
2427    return new EchoStatement(exprs,token.sourceStart, token2.sourceEnd);
2428    }
2429 }
2430
2431 GlobalStatement GlobalStatement() :
2432 {
2433    Variable expr;
2434    final ArrayList vars = new ArrayList();
2435    final GlobalStatement global;
2436    final Token token, token2;
2437    int pos;
2438 }
2439 {
2440   token = <GLOBAL>
2441     expr = Variable()
2442     {vars.add(expr);pos = expr.sourceEnd+1;}
2443   (<COMMA>
2444     expr = Variable()
2445     {vars.add(expr);pos = expr.sourceEnd+1;}
2446   )*
2447   try {
2448     token2 = <SEMICOLON>
2449     {pos = token2.sourceEnd+1;}
2450   } catch (ParseException e) {
2451     errorMessage = "unexpected token : '"+ e.currentToken.next.image +"'. a ';' was expected";
2452     errorLevel   = ERROR;
2453     errorStart = pos;
2454     errorEnd   = pos;
2455     processParseExceptionDebug(e);
2456   }
2457     {
2458     final Variable[] variables = new Variable[vars.size()];
2459     vars.toArray(variables);
2460     global = new GlobalStatement(currentSegment,
2461                                  variables,
2462                                  token.sourceStart,
2463                                  pos);
2464     currentSegment.add(global);
2465     return global;}
2466 }
2467
2468 StaticStatement StaticStatement() :
2469 {
2470   final ArrayList vars = new ArrayList();
2471   VariableDeclaration expr;
2472   final Token token, token2;
2473   int pos;
2474 }
2475 {
2476   token = <STATIC> expr = VariableDeclarator() {vars.add(expr);pos = expr.sourceEnd+1;}
2477   (
2478     <COMMA> expr = VariableDeclarator() {vars.add(expr);pos = expr.sourceEnd+1;}
2479   )*
2480   try {
2481     token2 = <SEMICOLON>
2482     {pos = token2.sourceEnd+1;}
2483   } catch (ParseException e) {
2484     errorMessage = "unexpected token : '"+ e.currentToken.next.image +"'. a ';' was expected";
2485     errorLevel   = ERROR;
2486     errorStart = pos;
2487     errorEnd   = pos;
2488     processParseException(e);
2489   }
2490     {
2491     final VariableDeclaration[] variables = new VariableDeclaration[vars.size()];
2492     vars.toArray(variables);
2493     return new StaticStatement(variables,
2494                                token.sourceStart,
2495                                pos);}
2496 }
2497
2498 LabeledStatement LabeledStatement() :
2499 {
2500   final Token label;
2501   final Statement statement;
2502 }
2503 {
2504   label = <IDENTIFIER> <COLON> statement = Statement()
2505   {return new LabeledStatement(label.image,statement,label.sourceStart,statement.sourceEnd);}
2506 }
2507
2508 /**
2509  * A Block is
2510  * {
2511  * statements
2512  * }.
2513  * @return a block
2514  */
2515 Block Block() :
2516 {
2517   final ArrayList list = new ArrayList();
2518   Statement statement;
2519   final Token token, token2;
2520   int pos,start;
2521 }
2522 {
2523   try {
2524     token = <LBRACE>
2525     {pos = token.sourceEnd+1;start=token.sourceStart;}
2526   } catch (ParseException e) {
2527     errorMessage = "'{' expected";
2528     errorLevel   = ERROR;
2529     pos = PHPParser.token.sourceEnd+1;
2530     start=pos;
2531     errorStart = pos;
2532     errorEnd   = pos;
2533     processParseExceptionDebug(e);
2534   }
2535   ( statement = BlockStatement() {list.add(statement);pos = statement.sourceEnd+1;}
2536   | statement = htmlBlock()      {if (statement != null) {
2537                                     list.add(statement);
2538                                     pos = statement.sourceEnd+1;
2539                                   }
2540                                   pos = PHPParser.token.sourceEnd+1;
2541                                  }
2542   )*
2543   try {
2544     token2 = <RBRACE>
2545     {pos = token2.sourceEnd+1;}
2546   } catch (ParseException e) {
2547     errorMessage = "unexpected token : '"+ e.currentToken.image +"', '}' expected";
2548     errorLevel   = ERROR;
2549     errorStart = pos;
2550     errorEnd   = pos;
2551     processParseExceptionDebug(e);
2552   }
2553   {
2554   final Statement[] statements = new Statement[list.size()];
2555   list.toArray(statements);
2556   return new Block(statements,start,pos);}
2557 }
2558
2559 Statement BlockStatement() :
2560 {
2561   final Statement statement;
2562 }
2563 {
2564   try {
2565     statement = Statement()         {if (phpDocument == currentSegment) pushOnAstNodes(statement);
2566                                      return statement;}
2567   } catch (ParseException e) {
2568     errorMessage = "unexpected token : '"+ e.currentToken.image +"', a statement was expected";
2569     errorLevel   = ERROR;
2570     errorStart = e.currentToken.sourceStart;
2571     errorEnd   = e.currentToken.sourceEnd;
2572     throw e;
2573   }
2574 | statement = ClassDeclaration()  {return statement;}
2575 | statement = MethodDeclaration() {if (phpDocument == currentSegment) pushOnAstNodes(statement);
2576                                    currentSegment.add((MethodDeclaration) statement);
2577                                    ((MethodDeclaration) statement).analyzeCode();
2578                                    return statement;}
2579 }
2580
2581 /**
2582  * A Block statement that will not contain any 'break'
2583  */
2584 Statement BlockStatementNoBreak() :
2585 {
2586   final Statement statement;
2587 }
2588 {
2589   statement = StatementNoBreak()  {return statement;}
2590 | statement = ClassDeclaration()  {return statement;}
2591 | statement = MethodDeclaration() {currentSegment.add((MethodDeclaration) statement);
2592                                    ((MethodDeclaration) statement).analyzeCode();
2593                                    return statement;}
2594 }
2595
2596 /**
2597  * used only by ForInit()
2598  */
2599 Expression[] LocalVariableDeclaration() :
2600 {
2601   final ArrayList list = new ArrayList();
2602   Expression var;
2603 }
2604 {
2605   var = Expression()
2606   {list.add(var);}
2607   ( <COMMA> var = Expression() {list.add(var);})*
2608   {
2609     final Expression[] vars = new Expression[list.size()];
2610     list.toArray(vars);
2611     return vars;
2612   }
2613 }
2614
2615 /**
2616  * used only by LocalVariableDeclaration().
2617  */
2618 VariableDeclaration LocalVariableDeclarator() :
2619 {
2620   final Variable varName;
2621   Expression initializer = null;
2622 }
2623 {
2624   varName = Variable() [ <ASSIGN> initializer = Expression() ]
2625   {
2626    if (initializer == null) {
2627     return new VariableDeclaration(currentSegment,
2628                                    varName,
2629                                    varName.sourceStart,
2630                                    varName.sourceEnd);
2631    }
2632     return new VariableDeclaration(currentSegment,
2633                                    varName,
2634                                    initializer,
2635                                    VariableDeclaration.EQUAL,
2636                                    varName.sourceStart);
2637   }
2638 }
2639
2640 EmptyStatement EmptyStatement() :
2641 {
2642   final Token token;
2643 }
2644 {
2645   token = <SEMICOLON>
2646   {return new EmptyStatement(token.sourceStart,token.sourceEnd);}
2647 }
2648
2649 /**
2650  * used only by StatementExpressionList() which is used only by ForInit() and ForStatement()
2651  */
2652 Expression StatementExpression() :
2653 {
2654   final Expression expr;
2655   final Token operator;
2656 }
2657 {
2658   expr = PreIncDecExpression() {return expr;}
2659 |
2660   expr = PrimaryExpression()
2661   [ operator = <PLUS_PLUS> {return new PostfixedUnaryExpression(expr,
2662                                                                 OperatorIds.PLUS_PLUS,
2663                                                                 operator.sourceEnd);}
2664   | operator = <MINUS_MINUS> {return new PostfixedUnaryExpression(expr,
2665                                                                   OperatorIds.MINUS_MINUS,
2666                                                                   operator.sourceEnd);}
2667   ]
2668   {return expr;}
2669 }
2670
2671 SwitchStatement SwitchStatement() :
2672 {
2673   Expression variable;
2674   final AbstractCase[] cases;
2675   final Token switchToken,lparenToken,rparenToken;
2676   int pos;
2677 }
2678 {
2679   switchToken = <SWITCH> {pos = switchToken.sourceEnd+1;}
2680   try {
2681     lparenToken = <LPAREN>
2682     {pos = lparenToken.sourceEnd+1;}
2683   } catch (ParseException e) {
2684     errorMessage = "'(' expected after 'switch'";
2685     errorLevel   = ERROR;
2686     errorStart = pos;
2687     errorEnd   = pos;
2688     processParseExceptionDebug(e);
2689   }
2690   try {
2691     variable = Expression() {pos = variable.sourceEnd+1;}
2692   } catch (ParseException e) {
2693     if (errorMessage != null) {
2694       throw e;
2695     }
2696     errorMessage = "expression expected";
2697     errorLevel   = ERROR;
2698     errorStart = pos;
2699     errorEnd   = pos;
2700     processParseExceptionDebug(e);
2701     variable = new ConstantIdentifier(SYNTAX_ERROR_CHAR,pos,pos);
2702   }
2703   try {
2704     rparenToken = <RPAREN> {pos = rparenToken.sourceEnd+1;}
2705   } catch (ParseException e) {
2706     errorMessage = "')' expected";
2707     errorLevel   = ERROR;
2708     errorStart = pos;
2709     errorEnd   = pos;
2710     processParseExceptionDebug(e);
2711   }
2712   (  cases = switchStatementBrace()
2713    | cases = switchStatementColon(switchToken.sourceStart, switchToken.sourceEnd))
2714   {return new SwitchStatement(variable,
2715                               cases,
2716                               switchToken.sourceStart,
2717                               PHPParser.token.sourceEnd);}
2718 }
2719
2720 AbstractCase[] switchStatementBrace() :
2721 {
2722   AbstractCase cas;
2723   final ArrayList cases = new ArrayList();
2724   Token token;
2725   int pos;
2726 }
2727 {
2728   token = <LBRACE> {pos = token.sourceEnd;}
2729  ( cas = switchLabel0() {cases.add(cas);pos = cas.sourceEnd;})*
2730   try {
2731     token = <RBRACE>
2732     {pos = token.sourceEnd;}
2733   } catch (ParseException e) {
2734     errorMessage = "'}' expected";
2735     errorLevel   = ERROR;
2736     errorStart = pos+1;
2737     errorEnd   = pos+1;
2738     processParseExceptionDebug(e);
2739   }
2740   {
2741     final AbstractCase[] abcase = new AbstractCase[cases.size()];
2742     cases.toArray(abcase);
2743     return abcase;
2744   }
2745 }
2746
2747 /**
2748  * A Switch statement with : ... endswitch;
2749  * @param start the begin offset of the switch
2750  * @param end the end offset of the switch
2751  */
2752 AbstractCase[] switchStatementColon(final int start, final int end) :
2753 {
2754   AbstractCase cas;
2755   final ArrayList cases = new ArrayList();
2756   Token token;
2757   int pos;
2758 }
2759 {
2760   token = <COLON> {pos = token.sourceEnd;}
2761   {try {
2762   setMarker(fileToParse,
2763             "Ugly syntax detected, you should switch () {...} instead of switch (): ... enswitch;",
2764             start,
2765             end,
2766             INFO,
2767             "Line " + token.beginLine);
2768   } catch (CoreException e) {
2769     PHPeclipsePlugin.log(e);
2770   }}
2771   ( cas = switchLabel0() {cases.add(cas);pos = cas.sourceEnd;})*
2772   try {
2773     token = <ENDSWITCH> {pos = token.sourceEnd;}
2774   } catch (ParseException e) {
2775     errorMessage = "'endswitch' expected";
2776     errorLevel   = ERROR;
2777     errorStart = pos+1;
2778     errorEnd   = pos+1;
2779     processParseExceptionDebug(e);
2780   }
2781   try {
2782     token = <SEMICOLON> {pos = token.sourceEnd;}
2783   } catch (ParseException e) {
2784     errorMessage = "';' expected after 'endswitch' keyword";
2785     errorLevel   = ERROR;
2786     errorStart = pos+1;
2787     errorEnd   = pos+1;
2788     processParseExceptionDebug(e);
2789   }
2790   {
2791     final AbstractCase[] abcase = new AbstractCase[cases.size()];
2792     cases.toArray(abcase);
2793     return abcase;
2794   }
2795 }
2796
2797 AbstractCase switchLabel0() :
2798 {
2799   final Expression expr;
2800   Statement statement;
2801   final ArrayList stmts = new ArrayList();
2802   final Token token = PHPParser.token;
2803 }
2804 {
2805   expr = SwitchLabel()
2806   ( statement = BlockStatementNoBreak() {stmts.add(statement);}
2807   | statement = htmlBlock()             {if (statement != null) {stmts.add(statement);}}
2808   | statement = BreakStatement()        {stmts.add(statement);})*
2809   //[ statement = BreakStatement()        {stmts.add(statement);}]
2810   {
2811     final int listSize = stmts.size();
2812     final Statement[] stmtsArray = new Statement[listSize];
2813     stmts.toArray(stmtsArray);
2814     if (expr == null) {//it's a default
2815       return new DefaultCase(stmtsArray,token.sourceStart,stmtsArray[listSize-1].sourceEnd);
2816     }
2817     if (listSize != 0) {
2818       return new Case(expr,stmtsArray,expr.sourceStart,stmtsArray[listSize-1].sourceEnd);
2819     } else {
2820       return new Case(expr,stmtsArray,expr.sourceStart,expr.sourceEnd);
2821     }
2822   }
2823 }
2824
2825 /**
2826  * A SwitchLabel.
2827  * case Expression() :
2828  * default :
2829  * @return the if it was a case and null if not
2830  */
2831 Expression SwitchLabel() :
2832 {
2833   final Expression expr;
2834 }
2835 {
2836   token = <CASE>
2837   try {
2838     expr = Expression()
2839   } catch (ParseException e) {
2840     if (errorMessage != null) throw e;
2841     errorMessage = "expression expected after 'case' keyword";
2842     errorLevel   = ERROR;
2843     errorStart = token.sourceEnd +1;
2844     errorEnd   = token.sourceEnd +1;
2845     throw e;
2846   }
2847   try {
2848     token = <COLON>
2849   } catch (ParseException e) {
2850     errorMessage = "':' expected after case expression";
2851     errorLevel   = ERROR;
2852     errorStart = expr.sourceEnd+1;
2853     errorEnd   = expr.sourceEnd+1;
2854     processParseExceptionDebug(e);
2855   }
2856   {return expr;}
2857 |
2858   token = <_DEFAULT>
2859   try {
2860     <COLON>
2861   } catch (ParseException e) {
2862     errorMessage = "':' expected after 'default' keyword";
2863     errorLevel   = ERROR;
2864     errorStart = token.sourceEnd+1;
2865     errorEnd   = token.sourceEnd+1;
2866     processParseExceptionDebug(e);
2867   }
2868   {return null;}
2869 }
2870
2871 Break BreakStatement() :
2872 {
2873   Expression expression = null;
2874   final Token token, token2;
2875   int pos;
2876 }
2877 {
2878   token = <BREAK> {pos = token.sourceEnd+1;}
2879   [ expression = Expression() {pos = expression.sourceEnd+1;}]
2880   try {
2881     token2 = <SEMICOLON>
2882     {pos = token2.sourceEnd;}
2883   } catch (ParseException e) {
2884     errorMessage = "';' expected after 'break' keyword";
2885     errorLevel   = ERROR;
2886     errorStart = pos;
2887     errorEnd   = pos;
2888     processParseExceptionDebug(e);
2889   }
2890   {return new Break(expression, token.sourceStart, pos);}
2891 }
2892
2893 IfStatement IfStatement() :
2894 {
2895   final Expression condition;
2896   final IfStatement ifStatement;
2897   Token token;
2898 }
2899 {
2900   token = <IF> condition = Condition("if")
2901   ifStatement = IfStatement0(condition,token.sourceStart,token.sourceEnd)
2902   {return ifStatement;}
2903 }
2904
2905
2906 Expression Condition(final String keyword) :
2907 {
2908   final Expression condition;
2909 }
2910 {
2911   try {
2912     <LPAREN>
2913   } catch (ParseException e) {
2914     errorMessage = "'(' expected after " + keyword + " keyword";
2915     errorLevel   = ERROR;
2916     errorStart = PHPParser.token.sourceEnd + 1;
2917     errorEnd   = PHPParser.token.sourceEnd + 1;
2918     processParseExceptionDebug(e);
2919   }
2920   condition = Expression()
2921   try {
2922      <RPAREN>
2923   } catch (ParseException e) {
2924     errorMessage = "')' expected after " + keyword + " keyword";
2925     errorLevel   = ERROR;
2926     errorStart = condition.sourceEnd+1;
2927     errorEnd   = condition.sourceEnd+1;
2928     processParseExceptionDebug(e);
2929   }
2930   {return condition;}
2931 }
2932
2933 IfStatement IfStatement0(final Expression condition, final int start,final int end) :
2934 {
2935   Statement statement;
2936   final Statement stmt;
2937   final Statement[] statementsArray;
2938   ElseIf elseifStatement;
2939   Else elseStatement = null;
2940   final ArrayList stmts;
2941   final ArrayList elseIfList = new ArrayList();
2942   final ElseIf[] elseIfs;
2943   int pos = SimpleCharStream.getPosition();
2944   final int endStatements;
2945 }
2946 {
2947   <COLON>
2948   {stmts = new ArrayList();}
2949   (  statement = Statement() {stmts.add(statement);}
2950    | statement = htmlBlock() {if (statement != null) {stmts.add(statement);}})*
2951    {endStatements = SimpleCharStream.getPosition();}
2952    (elseifStatement = ElseIfStatementColon() {elseIfList.add(elseifStatement);})*
2953    [elseStatement = ElseStatementColon()]
2954
2955   {try {
2956   setMarker(fileToParse,
2957             "Ugly syntax detected, you should if () {...} instead of if (): ... endif;",
2958             start,
2959             end,
2960             INFO,
2961             "Line " + token.beginLine);
2962   } catch (CoreException e) {
2963     PHPeclipsePlugin.log(e);
2964   }}
2965   try {
2966     <ENDIF>
2967   } catch (ParseException e) {
2968     errorMessage = "'endif' expected";
2969     errorLevel   = ERROR;
2970     errorStart = SimpleCharStream.getPosition() - e.currentToken.next.image.length() + 1;
2971     errorEnd   = SimpleCharStream.getPosition() + 1;
2972     throw e;
2973   }
2974   try {
2975     <SEMICOLON>
2976   } catch (ParseException e) {
2977     errorMessage = "';' expected after 'endif' keyword";
2978     errorLevel   = ERROR;
2979     errorStart = SimpleCharStream.getPosition() - e.currentToken.next.image.length() + 1;
2980     errorEnd   = SimpleCharStream.getPosition() + 1;
2981     throw e;
2982   }
2983     {
2984     elseIfs = new ElseIf[elseIfList.size()];
2985     elseIfList.toArray(elseIfs);
2986     if (stmts.size() == 1) {
2987       return new IfStatement(condition,
2988                              (Statement) stmts.get(0),
2989                               elseIfs,
2990                               elseStatement,
2991                               pos,
2992                               SimpleCharStream.getPosition());
2993     } else {
2994       statementsArray = new Statement[stmts.size()];
2995       stmts.toArray(statementsArray);
2996       return new IfStatement(condition,
2997                              new Block(statementsArray,pos,endStatements),
2998                              elseIfs,
2999                              elseStatement,
3000                              pos,
3001                              SimpleCharStream.getPosition());
3002     }
3003     }
3004
3005 |
3006   (stmt = Statement() | stmt = htmlBlock())
3007   ( LOOKAHEAD(1) elseifStatement = ElseIfStatement() {elseIfList.add(elseifStatement);})*
3008   [ LOOKAHEAD(1)
3009     <ELSE>
3010     try {
3011       {pos = SimpleCharStream.getPosition();}
3012       statement = Statement()
3013       {elseStatement = new Else(statement,pos,SimpleCharStream.getPosition());}
3014     } catch (ParseException e) {
3015       if (errorMessage != null) {
3016         throw e;
3017       }
3018       errorMessage = "unexpected token '"+e.currentToken.next.image+"', a statement was expected";
3019       errorLevel   = ERROR;
3020       errorStart = SimpleCharStream.getPosition() - e.currentToken.next.image.length() + 1;
3021       errorEnd   = SimpleCharStream.getPosition() + 1;
3022       throw e;
3023     }
3024   ]
3025   {
3026     elseIfs = new ElseIf[elseIfList.size()];
3027     elseIfList.toArray(elseIfs);
3028     return new IfStatement(condition,
3029                            stmt,
3030                            elseIfs,
3031                            elseStatement,
3032                            pos,
3033                            SimpleCharStream.getPosition());}
3034 }
3035
3036 ElseIf ElseIfStatementColon() :
3037 {
3038   final Expression condition;
3039   Statement statement;
3040   final ArrayList list = new ArrayList();
3041   final Token elseifToken;
3042 }
3043 {
3044   elseifToken = <ELSEIF> condition = Condition("elseif")
3045   <COLON> (  statement = Statement() {list.add(statement);}
3046            | statement = htmlBlock() {if (statement != null) {list.add(statement);}})*
3047   {
3048   final int sizeList = list.size();
3049   final Statement[] stmtsArray = new Statement[sizeList];
3050   list.toArray(stmtsArray);
3051   return new ElseIf(condition,stmtsArray ,
3052                     elseifToken.sourceStart,
3053                     stmtsArray[sizeList-1].sourceEnd);}
3054 }
3055
3056 Else ElseStatementColon() :
3057 {
3058   Statement statement;
3059   final ArrayList list = new ArrayList();
3060   final Token elseToken;
3061 }
3062 {
3063   elseToken = <ELSE> <COLON> (  statement = Statement() {list.add(statement);}
3064                   | statement = htmlBlock() {if (statement != null) {list.add(statement);}})*
3065   {
3066   final int sizeList = list.size();
3067   final Statement[] stmtsArray = new Statement[sizeList];
3068   list.toArray(stmtsArray);
3069   return new Else(stmtsArray,elseToken.sourceStart,stmtsArray[sizeList-1].sourceEnd);}
3070 }
3071
3072 ElseIf ElseIfStatement() :
3073 {
3074   final Expression condition;
3075   //final Statement statement;
3076   final Token elseifToken;
3077   final Statement[] statement = new Statement[1];
3078 }
3079 {
3080   elseifToken = <ELSEIF> condition = Condition("elseif") statement[0] = Statement()
3081   {
3082   return new ElseIf(condition,statement,elseifToken.sourceStart,statement[0].sourceEnd);}
3083 }
3084
3085 WhileStatement WhileStatement() :
3086 {
3087   final Expression condition;
3088   final Statement action;
3089   final Token whileToken;
3090 }
3091 {
3092   whileToken = <WHILE>
3093     condition = Condition("while")
3094     action    = WhileStatement0(whileToken.sourceStart,whileToken.sourceEnd)
3095     {return new WhileStatement(condition,action,whileToken.sourceStart,action.sourceEnd);}
3096 }
3097
3098 Statement WhileStatement0(final int start, final int end) :
3099 {
3100   Statement statement;
3101   final ArrayList stmts = new ArrayList();
3102   final int pos = SimpleCharStream.getPosition();
3103 }
3104 {
3105   <COLON> (statement = Statement() {stmts.add(statement);})*
3106   {try {
3107   setMarker(fileToParse,
3108             "Ugly syntax detected, you should while () {...} instead of while (): ... endwhile;",
3109             start,
3110             end,
3111             INFO,
3112             "Line " + token.beginLine);
3113   } catch (CoreException e) {
3114     PHPeclipsePlugin.log(e);
3115   }}
3116   try {
3117     <ENDWHILE>
3118   } catch (ParseException e) {
3119     errorMessage = "'endwhile' expected";
3120     errorLevel   = ERROR;
3121     errorStart = SimpleCharStream.getPosition() - e.currentToken.next.image.length() + 1;
3122     errorEnd   = SimpleCharStream.getPosition() + 1;
3123     throw e;
3124   }
3125   try {
3126     <SEMICOLON>
3127     {
3128     final Statement[] stmtsArray = new Statement[stmts.size()];
3129     stmts.toArray(stmtsArray);
3130     return new Block(stmtsArray,pos,SimpleCharStream.getPosition());}
3131   } catch (ParseException e) {
3132     errorMessage = "';' expected after 'endwhile' keyword";
3133     errorLevel   = ERROR;
3134     errorStart = SimpleCharStream.getPosition() - e.currentToken.next.image.length() + 1;
3135     errorEnd   = SimpleCharStream.getPosition() + 1;
3136     throw e;
3137   }
3138 |
3139   statement = Statement()
3140   {return statement;}
3141 }
3142
3143 DoStatement DoStatement() :
3144 {
3145   final Statement action;
3146   final Expression condition;
3147   final Token token;
3148   Token token2 = null;
3149 }
3150 {
3151   token = <DO> action = Statement() <WHILE> condition = Condition("while")
3152   try {
3153     token2 = <SEMICOLON>
3154   } catch (ParseException e) {
3155     errorMessage = "unexpected token : '"+ e.currentToken.next.image +"'. A ';' was expected";
3156     errorLevel   = ERROR;
3157     errorStart = condition.sourceEnd+1;
3158     errorEnd   = condition.sourceEnd+1;
3159     processParseExceptionDebug(e);
3160   }
3161   {
3162     if (token2 == null) {
3163       return new DoStatement(condition,action,token.sourceStart,condition.sourceEnd);
3164     }
3165     return new DoStatement(condition,action,token.sourceStart,token2.sourceEnd);
3166   }
3167 }
3168
3169 ForeachStatement ForeachStatement() :
3170 {
3171   Statement statement = null;
3172   Expression expression = null;
3173   ArrayVariableDeclaration variable = null;
3174   Token foreachToken;
3175   Token lparenToken = null;
3176   Token asToken = null;
3177   Token rparenToken = null;
3178   int pos;
3179 }
3180 {
3181   foreachToken = <FOREACH>
3182   try {
3183     lparenToken = <LPAREN>
3184     {pos = lparenToken.sourceEnd+1;}
3185   } catch (ParseException e) {
3186     errorMessage = "'(' expected after 'foreach' keyword";
3187     errorLevel   = ERROR;
3188     errorStart = foreachToken.sourceEnd+1;
3189     errorEnd   = foreachToken.sourceEnd+1;
3190     processParseExceptionDebug(e);
3191     {pos = foreachToken.sourceEnd+1;}
3192   }
3193   try {
3194     expression = Expression()
3195     {pos = expression.sourceEnd+1;}
3196   } catch (ParseException e) {
3197     errorMessage = "variable expected";
3198     errorLevel   = ERROR;
3199     errorStart = pos;
3200     errorEnd   = pos;
3201     processParseExceptionDebug(e);
3202   }
3203   try {
3204     asToken = <AS>
3205     {pos = asToken.sourceEnd+1;}
3206   } catch (ParseException e) {
3207     errorMessage = "'as' expected";
3208     errorLevel   = ERROR;
3209     errorStart = pos;
3210     errorEnd   = pos;
3211     processParseExceptionDebug(e);
3212   }
3213   try {
3214     variable = ArrayVariable()
3215     {pos = variable.sourceEnd+1;}
3216   } catch (ParseException e) {
3217     if (errorMessage != null) throw e;
3218     errorMessage = "variable expected";
3219     errorLevel   = ERROR;
3220     errorStart = pos;
3221     errorEnd   = pos;
3222     processParseExceptionDebug(e);
3223   }
3224   try {
3225     rparenToken = <RPAREN>
3226     {pos = rparenToken.sourceEnd+1;}
3227   } catch (ParseException e) {
3228     errorMessage = "')' expected after 'foreach' keyword";
3229     errorLevel   = ERROR;
3230     errorStart = pos;
3231     errorEnd   = pos;
3232     processParseExceptionDebug(e);
3233   }
3234   try {
3235     statement = Statement()
3236     {pos = rparenToken.sourceEnd+1;}
3237   } catch (ParseException e) {
3238     if (errorMessage != null) throw e;
3239     errorMessage = "statement expected";
3240     errorLevel   = ERROR;
3241     errorStart = pos;
3242     errorEnd   = pos;
3243     processParseExceptionDebug(e);
3244   }
3245   {return new ForeachStatement(expression,
3246                                variable,
3247                                statement,
3248                                foreachToken.sourceStart,
3249                                statement.sourceEnd);}
3250
3251 }
3252
3253 /**
3254  * a for declaration.
3255  * @return a node representing the for statement
3256  */
3257 ForStatement ForStatement() :
3258 {
3259 final Token token,tokenEndFor,token2,tokenColon;
3260 int pos;
3261 Expression[] initializations = null;
3262 Expression condition = null;
3263 Expression[] increments = null;
3264 Statement action;
3265 final ArrayList list = new ArrayList();
3266 }
3267 {
3268   token = <FOR>
3269   try {
3270     <LPAREN>
3271   } catch (ParseException e) {
3272     errorMessage = "'(' expected after 'for' keyword";
3273     errorLevel   = ERROR;
3274     errorStart = token.sourceEnd;
3275     errorEnd   = token.sourceEnd +1;
3276     processParseExceptionDebug(e);
3277   }
3278      [ initializations = ForInit() ] <SEMICOLON>
3279      [ condition = Expression() ] <SEMICOLON>
3280      [ increments = StatementExpressionList() ] <RPAREN>
3281     (
3282       action = Statement()
3283       {return new ForStatement(initializations,
3284                                condition,
3285                                increments,
3286                                action,
3287                                token.sourceStart,
3288                                action.sourceEnd);}
3289     |
3290       tokenColon = <COLON> {pos = tokenColon.sourceEnd+1;}
3291       (action = Statement() {list.add(action);pos = action.sourceEnd+1;})*
3292       {
3293         try {
3294         setMarker(fileToParse,
3295                   "Ugly syntax detected, you should for () {...} instead of for (): ... endfor;",
3296                   token.sourceStart,
3297                   token.sourceEnd,
3298                   INFO,
3299                   "Line " + token.beginLine);
3300         } catch (CoreException e) {
3301           PHPeclipsePlugin.log(e);
3302         }
3303       }
3304       try {
3305         tokenEndFor = <ENDFOR>
3306         {pos = tokenEndFor.sourceEnd+1;}
3307       } catch (ParseException e) {
3308         errorMessage = "'endfor' expected";
3309         errorLevel   = ERROR;
3310         errorStart = pos;
3311         errorEnd   = pos;
3312         processParseExceptionDebug(e);
3313       }
3314       try {
3315         token2 = <SEMICOLON>
3316         {pos = token2.sourceEnd+1;}
3317       } catch (ParseException e) {
3318         errorMessage = "';' expected after 'endfor' keyword";
3319         errorLevel   = ERROR;
3320         errorStart = pos;
3321         errorEnd   = pos;
3322         processParseExceptionDebug(e);
3323       }
3324       {
3325       final Statement[] stmtsArray = new Statement[list.size()];
3326       list.toArray(stmtsArray);
3327       return new ForStatement(initializations,
3328                               condition,
3329                               increments,
3330                               new Block(stmtsArray,
3331                                         stmtsArray[0].sourceStart,
3332                                         stmtsArray[stmtsArray.length-1].sourceEnd),
3333                               token.sourceStart,
3334                               pos);}
3335     )
3336 }
3337
3338 Expression[] ForInit() :
3339 {
3340   final Expression[] exprs;
3341 }
3342 {
3343   LOOKAHEAD(LocalVariableDeclaration())
3344   exprs = LocalVariableDeclaration()
3345   {return exprs;}
3346 |
3347   exprs = StatementExpressionList()
3348   {return exprs;}
3349 }
3350
3351 Expression[] StatementExpressionList() :
3352 {
3353   final ArrayList list = new ArrayList();
3354   final Expression expr;
3355 }
3356 {
3357   expr = Expression()   {list.add(expr);}
3358   (<COMMA> Expression() {list.add(expr);})*
3359   {
3360     final Expression[] exprsArray = new Expression[list.size()];
3361     list.toArray(exprsArray);
3362     return exprsArray;
3363   }
3364 }
3365
3366 Continue ContinueStatement() :
3367 {
3368   Expression expr = null;
3369   final Token token;
3370   Token token2 = null;
3371 }
3372 {
3373   token = <CONTINUE> [ expr = Expression() ]
3374   try {
3375     token2 = <SEMICOLON>
3376   } catch (ParseException e) {
3377     errorMessage = "';' expected after 'continue' statement";
3378     errorLevel   = ERROR;
3379     if (expr == null) {
3380       errorStart = token.sourceEnd+1;
3381       errorEnd   = token.sourceEnd+1;
3382     } else {
3383       errorStart = expr.sourceEnd+1;
3384       errorEnd   = expr.sourceEnd+1;
3385     }
3386     processParseExceptionDebug(e);
3387   }
3388   {
3389     if (token2 == null) {
3390       if (expr == null) {
3391         return new Continue(expr,token.sourceStart,token.sourceEnd);
3392       }
3393       return new Continue(expr,token.sourceStart,expr.sourceEnd);
3394     }
3395     return new Continue(expr,token.sourceStart,token2.sourceEnd);
3396   }
3397 }
3398
3399 ReturnStatement ReturnStatement() :
3400 {
3401   Expression expr = null;
3402   final Token token;
3403   Token token2 = null;
3404 }
3405 {
3406   token = <RETURN> [ expr = Expression() ]
3407   try {
3408     token2 = <SEMICOLON>
3409   } catch (ParseException e) {
3410     errorMessage = "';' expected after 'return' statement";
3411     errorLevel   = ERROR;
3412     if (expr == null) {
3413       errorStart = token.sourceEnd+1;
3414       errorEnd   = token.sourceEnd+1;
3415     } else {
3416       errorStart = expr.sourceEnd+1;
3417       errorEnd   = expr.sourceEnd+1;
3418     }
3419     processParseExceptionDebug(e);
3420   }
3421   {
3422     if (token2 == null) {
3423       if (expr == null) {
3424         return new ReturnStatement(expr,token.sourceStart,token.sourceEnd);
3425       }
3426       return new ReturnStatement(expr,token.sourceStart,expr.sourceEnd);
3427     }
3428     return new ReturnStatement(expr,token.sourceStart,token2.sourceEnd);
3429   }
3430 }
3431