View Javadoc

    1   /**
    2    * BSD-style license; for more info see http://pmd.sourceforge.net/license.html
    3    */
    4   package net.sourceforge.pmd.lang.ecmascript.ast;
    5
    6   import static org.junit.Assert.assertEquals;
    7
    8   import java.io.Reader;
    9   import java.io.StringReader;
    10  import java.util.List;
    11
    12  import net.sourceforge.pmd.PMD;
    13  import net.sourceforge.pmd.lang.ast.Node;
    14  import net.sourceforge.pmd.lang.ecmascript.EcmascriptParserOptions;
    15
    16  import org.junit.Test;
    17  import org.mozilla.javascript.ast.AstRoot;
    18
    19  public class EcmascriptParserTest {
    20
    21      private EcmascriptNode<AstRoot> parse(String code) {
    22          EcmascriptParser parser = new EcmascriptParser(new EcmascriptParserOptions());
    23          Reader sourceCode = new StringReader(code);
    24          return parser.parse(sourceCode);
    25      }
    26
    27      @Test
    28      public void testLineNumbers() {
    29      EcmascriptNode<AstRoot> node = parse(SOURCE_CODE);
    30  	assertEquals(1, node.getBeginLine());
    31  	assertEquals(1, node.getBeginColumn());
    32  	assertEquals(3, node.getEndLine());
    33  	assertEquals(1, node.getEndColumn());
    34
    35  	Node child = node.getFirstChildOfType(ASTFunctionNode.class);
    36  	assertEquals(1, child.getBeginLine());
    37  	assertEquals(1, child.getBeginColumn());
    38  	assertEquals(3, child.getEndLine());
    39  	assertEquals(1, child.getEndColumn());
    40
    41  	child = node.getFirstDescendantOfType(ASTFunctionCall.class);
    42  	assertEquals(2, child.getBeginLine());
    43  	assertEquals(3, child.getBeginColumn());
    44  	assertEquals(2, child.getEndLine());
    45  	assertEquals(16, child.getEndColumn());
    46      }
    47
    48      /**
    49       * Test bug https://sourceforge.net/p/pmd/bugs/1118/
    50       */
    51      @Test
    52      public void testArrayAccess() {
    53          EcmascriptNode<AstRoot> node = parse("function a() { b['a'] = 1; c[1] = 2; }");
    54          List<ASTElementGet> arrays = node.findDescendantsOfType(ASTElementGet.class);
    55          assertEquals("b", arrays.get(0).getTarget().getImage());
    56          assertEquals("a", arrays.get(0).getElement().getImage());
    57          assertEquals("c", arrays.get(1).getTarget().getImage());
    58          assertEquals("1", arrays.get(1).getElement().getImage());
    59      }
    60
    61      private static final String SOURCE_CODE =
    62  	    "function a() {" + PMD.EOL
    63  	  + "  alert('hello');" + PMD.EOL
    64  	  + "}" + PMD.EOL;
    65  }