KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > armedbear > j > PythonSyntaxIterator


1 /*
2  * PythonSyntaxIterator.java
3  *
4  * Copyright (C) 2002 Peter Graves
5  * $Id: PythonSyntaxIterator.java,v 1.1.1.1 2002/09/24 16:08:45 piso Exp $
6  *
7  * This program is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU General Public License
9  * as published by the Free Software Foundation; either version 2
10  * of the License, or (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with this program; if not, write to the Free Software
19  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
20  */

21
22 package org.armedbear.j;
23
24 public final class PythonSyntaxIterator extends DefaultSyntaxIterator
25 {
26     private static final int STATE_NEUTRAL = 0;
27     private static final int STATE_QUOTE = 1;
28
29     public PythonSyntaxIterator(Position pos)
30     {
31         super(pos);
32     }
33
34     // Returns char array with syntactic whitespace (quotes and comments)
35
// replaced with actual space characters.
36
public char[] hideSyntacticWhitespace(String JavaDoc s)
37     {
38         char[] chars = s.toCharArray();
39         char quoteChar = 0;
40         int state = STATE_NEUTRAL;
41         final int length = chars.length;
42         for (int i = 0; i < length; i++) {
43             char c = chars[i];
44             if (c == '\\' && i < length-1) {
45                 // Escape!
46
chars[++i] = ' ';
47             } else if (state == STATE_QUOTE) {
48                 chars[i] = ' ';
49                 if (c == quoteChar)
50                     state = STATE_NEUTRAL;
51             } else if (c == '"' || c == '\'') {
52                 quoteChar = c;
53                 state = STATE_QUOTE;
54                 chars[i] = ' ';
55             }
56         }
57         // Handle comment part if any.
58
int index = -1;
59         for (int i = 0; i < length; i++) {
60             if (chars[i] == '#') {
61                 if (i > 0) {
62                     // Ignore '#' if escaped.
63
char c = chars[i-1];
64                     if (c == '\\')
65                         continue;
66                 }
67                 // Otherwise the rest of the line is a comment.
68
index = i;
69                 break;
70             }
71         }
72         if (index >= 0) {
73             for (int i = index; i < length; i++)
74                 chars[i] = ' ';
75         }
76         return chars;
77     }
78 }
79
Popular Tags