View Javadoc
1   /**
2    * BSD-style license; for more info see http://pmd.sourceforge.net/license.html
3    */
4   package net.sourceforge.pmd.lang.java.symboltable;
5   
6   import java.util.List;
7   
8   import net.sourceforge.pmd.lang.LanguageRegistry;
9   import net.sourceforge.pmd.lang.java.JavaLanguageModule;
10  import net.sourceforge.pmd.lang.java.ast.ASTLambdaExpression;
11  import net.sourceforge.pmd.lang.symboltable.NameDeclaration;
12  
13  import org.junit.Assert;
14  import org.junit.Test;
15  
16  public class ScopeAndDeclarationFinderTest extends STBBaseTst {
17  
18      /**
19       * Unit test for https://sourceforge.net/p/pmd/bugs/1317/
20       */
21      @Test
22      public void testJava8LambdaScoping() {
23          String source = "public class MultipleLambdas {\n" +
24                  "  Observer a = (o, arg) -> System.out.println(\"a:\" + arg);\n" +
25                  "  Observer b = (o, arg) -> System.out.println(\"b:\" + arg);\n" +
26                  "}";
27          parseCode(source, LanguageRegistry.getLanguage(JavaLanguageModule.NAME).getVersion("1.8"));
28  
29          List<ASTLambdaExpression> lambdas = acu.findDescendantsOfType(ASTLambdaExpression.class);
30          Assert.assertEquals(2, lambdas.size());
31          LocalScope scope1 = (LocalScope)lambdas.get(0).getScope();
32          LocalScope scope2 = (LocalScope)lambdas.get(1).getScope();
33          Assert.assertNotSame(scope1, scope2);
34  
35          for (ASTLambdaExpression l : lambdas) {
36              LocalScope scope = (LocalScope)l.getScope();
37              Assert.assertEquals(2, scope.getVariableDeclarations().size());
38              Assert.assertTrue(scope.contains(new JavaNameOccurrence(null, "o")));
39              Assert.assertTrue(scope.contains(new JavaNameOccurrence(null, "arg")));
40              NameDeclaration decl = scope.findVariableHere(new JavaNameOccurrence(null, "arg"));
41              Assert.assertEquals(1, scope.getVariableDeclarations().get(decl).size());
42          }
43      }
44  }