repo
stringlengths 1
191
⌀ | file
stringlengths 23
351
| code
stringlengths 0
5.32M
| file_length
int64 0
5.32M
| avg_line_length
float64 0
2.9k
| max_line_length
int64 0
288k
| extension_type
stringclasses 1
value |
---|---|---|---|---|---|---|
depends
|
depends-master/src/main/java/depends/entity/CandidateTypes.java
|
/*
MIT License
Copyright (c) 2018-2019 Gang ZHANG
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package depends.entity;
import depends.relations.IBindingResolver;
import depends.relations.Relation;
import java.util.*;
public class CandidateTypes extends TypeEntity {
private List<TypeEntity> candidateTypes;
public CandidateTypes() {
candidateTypes = new ArrayList<>();
}
public CandidateTypes(List<TypeEntity> candidateTypes, Integer id) {
super(GenericName.build("candidateTypes"), null, id);
this.candidateTypes = candidateTypes;
}
public List<TypeEntity> getCandidateTypes() {
return candidateTypes;
}
@Override
public Collection<TypeEntity> getInheritedTypes() {
List<TypeEntity> result = new ArrayList<>();
for (TypeEntity type:candidateTypes) {
result.addAll(type.getInheritedTypes());
}
return result;
}
@Override
public Collection<TypeEntity> getImplementedTypes() {
List<TypeEntity> result = new ArrayList<>();
for (TypeEntity type:candidateTypes) {
result.addAll(type.getImplementedTypes());
}
return result;
}
@Override
public ArrayList<FunctionEntity> getFunctions() {
ArrayList<FunctionEntity> result = new ArrayList<>();
for (TypeEntity type:candidateTypes) {
result.addAll(type.getFunctions());
}
return result;
}
@Override
public TypeEntity getInheritedType() {
return inheritedType;
}
@Override
public List<Entity> lookupFunctionInVisibleScope(GenericName functionName) {
List<Entity> functions = new ArrayList<>();
for (TypeEntity type:candidateTypes) {
List<Entity> f = type.lookupFunctionInVisibleScope(functionName);
if (f!=null) {
functions.addAll(f);
}
}
if (functions.size()==0)
return null;
return functions;
}
@Override
public Entity lookupVarInVisibleScope(GenericName varName) {
for (TypeEntity type:candidateTypes) {
Entity v = type.lookupVarInVisibleScope(varName);
if (v!=null) return v;
}
return null;
}
@Override
public VarEntity lookupVarLocally(String varName) {
for (TypeEntity type:candidateTypes) {
VarEntity v = type.lookupVarLocally(varName);
if (v!=null) return v;
}
return null;
}
@Override
public TypeEntity getType() {
if (candidateTypes.size()>0) return candidateTypes.get(0);
return null;
}
@Override
public void inferLocalLevelEntities(IBindingResolver bindingResolver) {
System.err.println("error: inferLocalLevelEntities should not been invoked");
super.inferLocalLevelEntities(bindingResolver);
}
@Override
public void addImplements(GenericName typeName) {
System.err.println("error: addImplements should not been invoked");
super.addImplements(typeName);
}
@Override
public void addExtends(GenericName typeName) {
System.err.println("error: addExtends should not been invoked");
super.addExtends(typeName);
}
@Override
public void addVar(VarEntity var) {
System.err.println("error: addVar should not been invoked");
super.addVar(var);
}
@Override
public ArrayList<VarEntity> getVars() {
System.err.println("error: getVars should not been invoked");
return super.getVars();
}
@Override
public void addFunction(FunctionEntity functionEntity) {
System.err.println("error: addFunction should not been invoked");
super.addFunction(functionEntity);
}
@Override
public HashMap<Object, Expression> expressions() {
System.err.println("error: expressions should not been invoked");
return super.expressions();
}
@Override
public void addExpression(Object key, Expression expression) {
System.err.println("error: addExpression should not been invoked");
super.addExpression(key, expression);
}
public void resolveExpressions(IBindingResolver bindingResolver) {
System.err.println("error: resolveExpressions should not been invoked");
super.resolveExpressions(bindingResolver);
}
@Override
public void addMixin(GenericName moduleName) {
System.err.println("error: addMixin should not been invoked");
super.addMixin(moduleName);
}
@Override
public Collection<ContainerEntity> getResolvedMixins() {
System.err.println("error: getResolvedMixins should not been invoked");
return super.getResolvedMixins();
}
@Override
public void addAnnotation(GenericName name) {
System.err.println("error: addAnnotation should not been invoked");
super.addAnnotation(name);
}
@Override
public Collection<Entity> getResolvedTypeParameters() {
System.err.println("error: getResolvedTypeParameters should not been invoked");
return super.getResolvedTypeParameters();
}
@Override
public Collection<Entity> getResolvedAnnotations() {
System.err.println("error: getResolvedAnnotations should not been invoked");
return super.getResolvedAnnotations();
}
@Override
public boolean isGenericTypeParameter(GenericName rawType) {
System.err.println("error: isGenericTypeParameter should not been invoked");
return super.isGenericTypeParameter(rawType);
}
@Override
protected Collection<Entity> identiferToEntities(IBindingResolver bindingResolver, Collection<GenericName> identifiers) {
System.err.println("error: identiferToTypes should not been invoked");
return super.identiferToEntities(bindingResolver, identifiers);
}
@Override
public GenericName getRawName() {
return super.getRawName();
}
@Override
public Integer getId() {
return super.getId();
}
@Override
public void addRelation(Relation relation) {
System.err.println("error: addRelation should not been invoked");
super.addRelation(relation);
}
@Override
public ArrayList<Relation> getRelations() {
System.err.println("error: getRelations should not been invoked");
return super.getRelations();
}
@Override
public void addChild(Entity child) {
System.err.println("error: addChild should not been invoked");
super.addChild(child);
}
@Override
public Entity getParent() {
return null;
}
@Override
public void setParent(Entity parent) {
System.err.println("error: setParent should not been invoked");
super.setParent(parent);
}
@Override
public Collection<Entity> getChildren() {
List<Entity> children = new ArrayList<>();
for (Entity entity:this.candidateTypes) {
children.addAll(entity.getChildren());
}
return children;
}
@Override
public void setQualifiedName(String qualifiedName) {
System.err.println("error: setQualifiedName should not been invoked");
super.setQualifiedName(qualifiedName);
}
@Override
public void setRawName(GenericName rawName) {
System.err.println("error: setRawName should not been invoked");
super.setRawName(rawName);
}
@Override
public String getQualifiedName(boolean overrideFileWithPackage) {
System.err.println("error: getQualifiedName should not been invoked");
return super.getQualifiedName(overrideFileWithPackage);
}
@Override
public Entity getAncestorOfType(@SuppressWarnings("rawtypes") Class classType) {
return null;
}
@Override
public void inferEntities(IBindingResolver bindingResolver) {
System.err.println("error: inferEntities should not been invoked");
super.inferEntities(bindingResolver);
}
@Override
public String getDisplayName() {
System.err.println("error: getDisplayName should not been invoked");
return super.getDisplayName();
}
@Override
public Entity getByName(String name, HashSet<Entity> searched) {
Entity entity = super.getByName(name, searched);
if (entity!=null) return entity;
for (TypeEntity type:getCandidateTypes()) {
if (searched.contains(type)) continue;
Entity e = type.getByName(name, searched);
if (e !=null) return e;
}
return null;
}
}
| 8,606 | 26.586538 | 122 |
java
|
depends
|
depends-master/src/main/java/depends/entity/MultiDeclareEntities.java
|
/*
MIT License
Copyright (c) 2018-2019 Gang ZHANG
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package depends.entity;
import depends.relations.IBindingResolver;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
/**
* MultiDeclareEntity is a special container, which is used as a wrapper
* of multi-declaration. for example,
* in C++, a function could be declared in different place with the same signature.
*/
public class MultiDeclareEntities extends ContainerEntity {
List<Entity> entities = new ArrayList<>();
private boolean containsTypeEntity = false;
public MultiDeclareEntities(Entity entity, int id ) {
this.id = id;
setQualifiedName(entity.getQualifiedName());
setRawName(entity.getRawName());
add(entity);
}
@Override
public void inferLocalLevelEntities(IBindingResolver bindingResolver) {
for (Entity entity:entities) {
entity.inferLocalLevelEntities(bindingResolver);
}
}
public void add(Entity entity) {
entity.setMutliDeclare(this);
if (entity instanceof TypeEntity)
this.containsTypeEntity = true;
if (entity instanceof MultiDeclareEntities){
((MultiDeclareEntities)entity).entities.forEach(e->add(e));
}else {
entities.add(entity);
}
}
public List<Entity> getEntities() {
return entities;
}
@Override
public Collection<Entity> getChildren() {
List<Entity> children = new ArrayList<>();
for (Entity entity:entities) {
children.addAll(entity.getChildren());
}
return children;
}
@Override
public TypeEntity getType() {
for (Entity entity:entities) {
if(entity.getType()!=null);
return entity.getType();
}
return null;
}
public boolean isContainsTypeEntity() {
return containsTypeEntity;
}
@Override
public Entity getByName(String name, HashSet<Entity> searched) {
Entity entity = super.getByName(name, searched);
if (entity!=null) return entity;
if (isContainsTypeEntity()) {
for (Entity declaredEntitiy : getEntities()) {
if (declaredEntitiy instanceof TypeEntity &&
declaredEntitiy.getRawName().getName().equals(name)) {
return declaredEntitiy;
}
}
}
return null;
}
}
| 3,162 | 28.287037 | 83 |
java
|
depends
|
depends-master/src/main/java/depends/entity/ContainerEntity.java
|
/*
MIT License
Copyright (c) 2018-2019 Gang ZHANG
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package depends.entity;
import depends.entity.repo.EntityRepo;
import depends.relations.IBindingResolver;
import depends.relations.Relation;
import multilang.depends.util.file.TemporaryFile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.lang.ref.WeakReference;
import java.util.*;
/**
* ContainerEntity for example file, class, method, etc. they could contain
* vars, functions, ecpressions, type parameters, etc.
*/
public abstract class ContainerEntity extends DecoratedEntity {
private static final Logger logger = LoggerFactory.getLogger(ContainerEntity.class);
private ArrayList<VarEntity> vars;
private ArrayList<FunctionEntity> functions;
WeakReference<HashMap<Object, Expression>> expressionWeakReference;
private ArrayList<Expression> expressionList;
private int expressionCount = 0;
private Collection<GenericName> mixins;
private Collection<ContainerEntity> resolvedMixins;
private ArrayList<VarEntity> vars() {
if (vars==null)
vars = new ArrayList<>();
return this.vars;
}
private Collection<GenericName> mixins() {
if (mixins==null)
mixins = new ArrayList<>();
return this.mixins;
}
private ArrayList<FunctionEntity> functions() {
if (functions==null)
functions = new ArrayList<>();
return this.functions;
}
public ContainerEntity() {
}
public ContainerEntity(GenericName rawName, Entity parent, Integer id) {
super(rawName, parent, id);
}
public void addVar(VarEntity var) {
if (logger.isDebugEnabled()) {
logger.debug("var found: " + var.getRawName() + ":" + var.getRawType());
}
this.vars().add(var);
}
public ArrayList<VarEntity> getVars() {
if (vars==null)
return new ArrayList<>();
return this.vars();
}
public void addFunction(FunctionEntity functionEntity) {
this.functions().add(functionEntity);
}
public ArrayList<FunctionEntity> getFunctions() {
if (functions==null)
return new ArrayList<>();
return this.functions;
}
public HashMap<Object, Expression> expressions() {
if (expressionWeakReference==null)
expressionWeakReference= new WeakReference<HashMap<Object, Expression>>(new HashMap<>());
HashMap<Object, Expression> r = expressionWeakReference.get();
if (r==null) return new HashMap<>();
return r;
}
public void addExpression(Object key, Expression expression) {
expressions().put(key, expression);
expressionList().add(expression);
expressionCount = expressionList.size();
}
public boolean containsExpression(Object key) {
return expressions().containsKey(key);
}
/**
* For all data in the class, infer their types. Should be override in
* sub-classes
*/
public void inferLocalLevelEntities(IBindingResolver bindingResolver) {
super.inferLocalLevelEntities(bindingResolver);
for (VarEntity var : this.vars()) {
if (var.getParent()!=this) {
var.inferLocalLevelEntities(bindingResolver);
}
}
for (FunctionEntity func : this.getFunctions()) {
if (func.getParent()!=this) {
func.inferLocalLevelEntities(bindingResolver);
}
}
if (bindingResolver.isEagerExpressionResolve()) {
reloadExpression(bindingResolver.getRepo());
resolveExpressions(bindingResolver);
cacheExpressions();
}
resolvedMixins = identiferToContainerEntity(bindingResolver, getMixins());
}
private Collection<GenericName> getMixins() {
if (mixins==null)
return new ArrayList<>();
return mixins;
}
private Collection<ContainerEntity> identiferToContainerEntity(IBindingResolver bindingResolver, Collection<GenericName> identifiers) {
if (identifiers.size()==0) return null;
ArrayList<ContainerEntity> r = new ArrayList<>();
for (GenericName identifier : identifiers) {
Entity entity = bindingResolver.resolveName(this, identifier, true);
if (entity == null) {
continue;
}
if (entity instanceof ContainerEntity)
r.add((ContainerEntity) entity);
}
return r;
}
/**
* Resolve all expression's type
*
* @param bindingResolver
*/
public void resolveExpressions(IBindingResolver bindingResolver) {
if (this instanceof FunctionEntity) {
((FunctionEntity)this).linkReturnToLastExpression();
}
if (expressionList==null) return;
if(expressionList.size()>10000) return;
for (Expression expression : expressionList) {
// 1. if expression's type existed, break;
if (expression.getType() != null)
continue;
if (expression.isDot()) { // wait for previous
continue;
}
if (expression.getRawType() == null && expression.getIdentifier() == null)
continue;
// 2. if expression's rawType existed, directly infer type by rawType
// if expression's rawType does not existed, infer type based on identifiers
if (expression.getRawType() != null) {
expression.setType(bindingResolver.inferTypeFromName(this, expression.getRawType()), null, bindingResolver);
if (expression.getType() != null) {
continue;
}
}
if (expression.getIdentifier() != null) {
Entity entity = bindingResolver.resolveName(this, expression.getIdentifier(), true);
String composedName = expression.getIdentifier().toString();
Expression theExpr = expression;
if (entity==null) {
while(theExpr.getParent()!=null && theExpr.getParent().isDot()) {
theExpr = theExpr.getParent();
if (theExpr.getIdentifier()==null) break;
composedName = composedName + "." + theExpr.getIdentifier().toString();
entity = bindingResolver.resolveName(this, GenericName.build(composedName), true);
if (entity!=null)
break;
}
}
if (entity != null) {
expression.setType(entity.getType(), entity, bindingResolver);
continue;
}
if (expression.isCall()) {
List<Entity> funcs = this.lookupFunctionInVisibleScope(expression.getIdentifier());
if (funcs != null) {
for (Entity func:funcs) {
expression.setType(func.getType(), func, bindingResolver);
}
}
} else {
Entity varEntity = this.lookupVarInVisibleScope(expression.getIdentifier());
if (varEntity != null) {
expression.setType(varEntity.getType(), varEntity, bindingResolver);
}
}
}
}
}
public void cacheChildExpressions() {
cacheExpressions();
for (Entity child:getChildren()) {
if (child instanceof ContainerEntity) {
((ContainerEntity)child).cacheChildExpressions();
}
}
}
public void cacheExpressions() {
if (expressionWeakReference==null) return;
if (expressionList==null) return;
this.expressions().clear();
this.expressionWeakReference.clear();
cacheExpressionListToFile();
this.expressionList.clear();
this.expressionList=null;
this.expressionList = new ArrayList<>();
}
public void clearExpressions() {
if (expressionWeakReference==null) return;
if (expressionList==null) return;
this.expressions().clear();
this.expressionWeakReference.clear();
this.expressionList.clear();
this.expressionList=null;
this.expressionList = new ArrayList<>();
this.expressionUseList = null;
}
private void cacheExpressionListToFile() {
if (expressionCount ==0) return;
try {
FileOutputStream fileOut = new FileOutputStream(TemporaryFile.getInstance().exprPath(this.id));
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(this.expressionList);
out.close();
fileOut.close();
} catch (IOException e) {
e.printStackTrace();
}
}
@SuppressWarnings("unchecked")
public void reloadExpression(EntityRepo repo) {
if (expressionCount ==0) return;
try
{
FileInputStream fileIn = new FileInputStream(TemporaryFile.getInstance().exprPath(this.id));
ObjectInputStream in = new ObjectInputStream(fileIn);
expressionList = (ArrayList<Expression>) in.readObject();
if (expressionList==null) expressionList = new ArrayList<>();
for (Expression expr:expressionList) {
expr.reload(repo,expressionList);
}
in.close();
fileIn.close();
}catch(IOException | ClassNotFoundException i)
{
return;
}
}
public List<Expression> expressionList() {
if (expressionList==null)
expressionList = new ArrayList<>();
return expressionList;
}
public boolean containsExpression() {
return expressions().size() > 0;
}
/**
* The entry point of lookup functions. It will treat multi-declare entities and
* normal entity differently. - for multiDeclare entity, it means to lookup all
* entities - for normal entity, it means to lookup entities from current scope
* still root
*
* @param functionName
* @return
*/
public List<Entity> lookupFunctionInVisibleScope(GenericName functionName) {
List<Entity> functions = new ArrayList<>();
if (this.getMutliDeclare() != null) {
for (Entity fromEntity : this.getMutliDeclare().getEntities()) {
Entity f = lookupFunctionBottomUpTillTopContainer(functionName, fromEntity);
if (f != null) {
functions.add(f);
return functions;
}
}
} else {
ContainerEntity fromEntity = this;
Entity f = lookupFunctionBottomUpTillTopContainer(functionName, fromEntity);
if (f != null) {
functions.add(f);
return functions;
}
}
return null;
}
/**
* lookup function bottom up till the most outside container
*
* @param functionName
* @param fromEntity
* @return
*/
private Entity lookupFunctionBottomUpTillTopContainer(GenericName functionName, Entity fromEntity) {
while (fromEntity != null) {
if (fromEntity instanceof ContainerEntity) {
FunctionEntity func = ((ContainerEntity) fromEntity).lookupFunctionLocally(functionName);
if (func != null)
return func;
}
for (Entity child:this.getChildren()) {
if (child instanceof AliasEntity) {
if (child.getRawName().equals(functionName))
return child;
}
}
fromEntity = (ContainerEntity) this.getAncestorOfType(ContainerEntity.class);
}
return null;
}
/**
* lookup function in local entity. It could be override such as the type entity
* (it should also lookup the inherit/implemented types
*
* @param functionName
* @return
*/
public FunctionEntity lookupFunctionLocally(GenericName functionName) {
for (FunctionEntity func : getFunctions()) {
if (func.getRawName().equals(functionName))
return func;
}
return null;
}
/**
* The entry point of lookup var. It will treat multi-declare entities and
* normal entity differently. - for multiDeclare entity, it means to lookup all
* entities - for normal entity, it means to lookup entities from current scope
* still root
*
* @param varName
* @return
*/
public Entity lookupVarInVisibleScope(GenericName varName) {
ContainerEntity fromEntity = this;
return lookupVarBottomUpTillTopContainer(varName, fromEntity);
}
/**
* To found the var.
*
* @param fromEntity
* @param varName
* @return
*/
private Entity lookupVarBottomUpTillTopContainer(GenericName varName, ContainerEntity fromEntity) {
while (fromEntity != null) {
if (fromEntity instanceof ContainerEntity) {
VarEntity var = ((ContainerEntity) fromEntity).lookupVarLocally(varName);
if (var != null)
return var;
}
for (Entity child:this.getChildren()) {
if (child instanceof AliasEntity) {
if (child.getRawName().equals(varName))
return child;
}
}
fromEntity = (ContainerEntity) this.getAncestorOfType(ContainerEntity.class);
}
return null;
}
public VarEntity lookupVarLocally(GenericName varName) {
for (VarEntity var : getVars()) {
if (var.getRawName().equals(varName))
return var;
}
return null;
}
public VarEntity lookupVarLocally(String varName) {
return this.lookupVarLocally(GenericName.build(varName));
}
public void addMixin(GenericName moduleName) {
mixins().add(moduleName);
}
public Collection<ContainerEntity> getResolvedMixins() {
if (resolvedMixins==null) return new ArrayList<>();
return resolvedMixins;
}
HashMap<String,Set<Expression>> expressionUseList = null;
public void addRelation(Expression expression, Relation relation) {
String key = relation.getEntity().qualifiedName+relation.getType();
if (this.expressionUseList==null)
expressionUseList = new HashMap<>();
if (expressionUseList.containsKey(key)){
Set<Expression> expressions = expressionUseList.get(key);
for (Expression expr:expressions){
if (linkedExpr(expr,expression)) return;
}
}else{
expressionUseList.put(key,new HashSet<>());
}
expressionUseList.get(key).add(expression);
super.addRelation(relation);
}
private boolean linkedExpr(Expression a, Expression b) {
Expression parent = a.getParent();
while(parent!=null){
if (parent==b) return true;
parent = parent.getParent();
}
parent = b.getParent();
while(parent!=null){
if (parent==a) return true;
parent = parent.getParent();
}
return false;
}
}
| 13,993 | 28.901709 | 136 |
java
|
depends
|
depends-master/src/main/java/depends/entity/FunctionEntityProto.java
|
package depends.entity;
public class FunctionEntityProto extends FunctionEntity{
public FunctionEntityProto() {
super();
}
public FunctionEntityProto(GenericName simpleName, Entity parent, Integer id, GenericName returnType) {
super(simpleName,parent,id,returnType);
}
}
| 284 | 24.909091 | 107 |
java
|
depends
|
depends-master/src/main/java/depends/entity/Location.java
|
package depends.entity;
import java.io.Serializable;
public class Location implements Serializable {
Integer line = null;
public Integer getLine(){
return line;
}
public void setLine(int line){
this.line = line;
}
}
| 254 | 17.214286 | 47 |
java
|
depends
|
depends-master/src/main/java/depends/entity/FileEntity.java
|
/*
MIT License
Copyright (c) 2018-2019 Gang ZHANG
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package depends.entity;
import depends.importtypes.Import;
import depends.relations.IBindingResolver;
import java.util.*;
public class FileEntity extends TypeEntity {
private List<Import> importedNames = new ArrayList<>();
private boolean isInProjectScope = false;
private Collection<Entity> importedRelationEntities = new ArrayList<>();
private Collection<Entity> importedFiles = new ArrayList<>();
private Collection<Entity> importedTypes = new ArrayList<>();
private List<TypeEntity> declaredTypes = new ArrayList<>();
private ImportedFileCollector importedFileCollector = null;
private boolean fileAsModule = false;
private String moduleName = "";
public FileEntity() {}
public FileEntity(boolean fileAsModule,String fullName, int fileId, boolean isInProjectScope) {
super(GenericName.build(fullName), null, fileId);
setQualifiedName(fullName);
this.isInProjectScope = isInProjectScope;
this.fileAsModule = fileAsModule;
}
public FileEntity(boolean fileAsModule,String fullName, int fileId) {
this(fileAsModule,fullName, fileId, true);
}
public void addImport(Import imported) {
if (!importedNames.contains(imported))
importedNames.add(imported);
}
/**
* To match the imported name by suffix
* for example:
* import a.b.ClassX;
* the b.ClassX, ClassX , a.b.classX should be matched
* @param lastName
* @return
*/
public String importedSuffixMatch(String lastName) {
if (!lastName.startsWith("."))
lastName = "." + lastName;
for (Entity imported : this.importedTypes) {
String name = imported.getQualifiedName(true);
if (!name.startsWith("."))
name = "." + name;
if (imported.getQualifiedName(true).endsWith(lastName))
return imported.getQualifiedName(true);
}
return null;
}
@Override
public String getQualifiedName(boolean overrideFileWithPackage) {
if (this.getParent() == null ||
!(this.getParent() instanceof PackageEntity)) {
if (fileAsModule){
return super.getQualifiedName();
}
return "";
}
//parent is PackageEntity
if (!fileAsModule) {
return this.getParent().getQualifiedName();
}else {
if (moduleName==null || moduleName.equals("")){
return this.getParent().getQualifiedName();
}
return this.getParent().getQualifiedName() + "." +moduleName;
}
}
@Override
public void inferLocalLevelEntities(IBindingResolver bindingResolver) {
this.importedRelationEntities = bindingResolver.getImportedRelationEntities(importedNames);
this.importedTypes = bindingResolver.getImportedTypes(importedNames,this);
this.importedFiles = bindingResolver.getImportedFiles(importedNames);
super.inferLocalLevelEntities(bindingResolver);
}
public boolean isInProjectScope() {
return isInProjectScope;
}
public void setInProjectScope(boolean isInProjectScope) {
this.isInProjectScope = isInProjectScope;
}
public Collection<Entity> getImportedRelationEntities() {
return importedRelationEntities;
}
public Collection<Entity> getImportedFiles() {
return importedFiles;
}
public Collection<Entity> getImportedTypes() {
return importedTypes;
}
public List<TypeEntity> getDeclaredTypes() {
return this.declaredTypes;
}
public void addType(TypeEntity currentTypeEntity) {
this.declaredTypes.add(currentTypeEntity);
}
public Set<FileEntity> getImportedFilesInAllLevel() {
if (importedFileCollector==null)
importedFileCollector = new ImportedFileCollector(this);
return importedFileCollector.getFiles();
}
public List<Import> getImportedNames() {
return importedNames;
}
public void cacheAllExpressions() {
this.cacheChildExpressions();
}
@Override
public Entity getByName(String name, HashSet<Entity> searched) {
Entity entity = super.getByName(name, searched);
if (entity!=null) return entity;
for (TypeEntity type:getDeclaredTypes()) {
if (type.getRawName().getName().equals(name)||
suffixMatch(name,type.getQualifiedName())) {
return type;
}
}
return null;
}
private boolean suffixMatch(String name, String qualifiedName) {
if (qualifiedName.contains(".")) {
if (!name.startsWith(".")) name = "." +name;
return qualifiedName.endsWith(name);
}
else {
return qualifiedName.equals(name);
}
}
public void setModuleName(String moduleName) {
this.moduleName = moduleName;
}
}
| 5,397 | 28.497268 | 96 |
java
|
depends
|
depends-master/src/main/java/depends/entity/AnonymousBlock.java
|
/*
MIT License
Copyright (c) 2018-2019 Gang ZHANG
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package depends.entity;
import java.util.UUID;
public class AnonymousBlock extends ContainerEntity{
public AnonymousBlock(Entity parent, Integer id) {
super(GenericName.build(UUID.randomUUID().toString()), parent, id);
}
}
| 1,315 | 37.705882 | 78 |
java
|
depends
|
depends-master/src/main/java/depends/entity/FunctionEntityImpl.java
|
package depends.entity;
import depends.relations.IBindingResolver;
public class FunctionEntityImpl extends FunctionEntity {
Entity implementedFunction = null;
public FunctionEntityImpl() {
super();
}
public FunctionEntityImpl(GenericName simpleName, Entity parent, Integer id, GenericName returnType) {
super(simpleName,parent,id,returnType);
}
@Override
public void inferLocalLevelEntities(IBindingResolver bindingResolver) {
super.inferLocalLevelEntities(bindingResolver);
implementedFunction = bindingResolver.lookupTypeInImported((FileEntity)(getAncestorOfType(FileEntity.class)),this.getQualifiedName());
}
public Entity getImplemented() {
return implementedFunction;
}
}
| 708 | 28.541667 | 136 |
java
|
depends
|
depends-master/src/main/java/depends/entity/GenericName.java
|
package depends.entity;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class GenericName implements Serializable{
private static final long serialVersionUID = 1L;
private char[] name;
List<GenericName> arguments;
public GenericName(String name) {
this.name = name.toCharArray();
}
public GenericName(String name, List<GenericName> arguments) {
this.name = name.toCharArray();
this.arguments = arguments;
}
public boolean contains(String rawType) {
if (new String(name).contains(rawType)) return true;
return false;
}
public String getName() {
return new String(name);
}
public List<GenericName> getArguments() {
if (arguments==null) return new ArrayList<>();
return arguments;
}
@Override
public String toString() {
return new String(name) + (getArguments().size()>0?"(" + arguments + ")":"");
}
public GenericName replace(String from, String to) {
name = new String(name).replace(from, to).toCharArray();
for (GenericName arg:getArguments()) {
arg.replace(from, to);
}
return this;
}
public boolean startsWith(String prefix) {
if (name==null) return false;
return new String(name).startsWith(prefix);
}
public String uniqName() {
if (getArguments().size()==0) return new String(name);
StringBuffer sb = new StringBuffer();
sb.append(name);
if (getArguments().size()>0) {
for (GenericName arg:getArguments()) {
sb.append("__").append(arg.uniqName()).append("__");
}
}
return sb.toString();
}
public GenericName substring(int start) {
return new GenericName(new String(this.name).substring(start));
}
public boolean isNull() {
return name==null;
}
public static GenericName build(String name) {
if (name==null) return null;
return new GenericName(name);
}
public static GenericName build(String name, List<GenericName> arguments) {
return new GenericName(name,arguments);
}
public boolean find(GenericName rawType) {
//if (this.equals(rawType)) return true;
for (GenericName subType:this.getArguments()) {
if (subType.equals(rawType)) return true;
boolean found = subType.find(rawType);
if (found) return true;
}
return false;
}
public void appendArguments(List<GenericName> parameters) {
if (this.arguments==null) this.arguments = new ArrayList<>();
this.arguments.addAll(parameters);
}
public void appendArguments(GenericName parameter) {
if (this.arguments==null) this.arguments = new ArrayList<>();
this.arguments.add(parameter);
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((arguments == null) ? 0 : arguments.hashCode());
result = prime * result + Arrays.hashCode(name);
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
GenericName other = (GenericName) obj;
if (this.getArguments() == null) {
if (other.getArguments() != null)
return false;
} else if (!getArguments().equals(other.getArguments()))
return false;
if (!Arrays.equals(name, other.name))
return false;
return true;
}
}
| 3,226 | 26.347458 | 79 |
java
|
depends
|
depends-master/src/main/java/depends/entity/repo/IdGenerator.java
|
/*
MIT License
Copyright (c) 2018-2019 Gang ZHANG
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package depends.entity.repo;
public interface IdGenerator {
/**
* Generate a global unique ID for entity
* @return the unique id
*/
Integer generateId();
}
| 1,245 | 34.6 | 78 |
java
|
depends
|
depends-master/src/main/java/depends/entity/repo/BuiltInType.java
|
/*
MIT License
Copyright (c) 2018-2019 Gang ZHANG
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package depends.entity.repo;
import depends.entity.FunctionCall;
import depends.entity.TypeEntity;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public abstract class BuiltInType {
public BuiltInType(){
createBuiltInTypes();
}
/**
* Init the build in types data
*/
private void createBuiltInTypes() {
for(String prefix: getBuiltInTypePrefix()) {
builtInPrefix.add(prefix);
}
for (String type: getBuiltInTypeName()) {
builtInType.add(type);
}
for (String method:getBuiltInMethods()) {
builtInMethod.add(method);
}
}
protected String[] getBuiltInMethods(){return new String[]{};}
protected String[] getBuiltInTypeName(){return new String[]{};}
protected String[] getBuiltInTypePrefix() {return new String[]{};}
private Set<String> builtInType = new HashSet<>();
private Set<String> builtInPrefix = new HashSet<>();
private Set<String> builtInMethod = new HashSet<>();
/**
* To determine whether a type name is built-in
* @param typeName
* @return
*/
public boolean isBuiltInType(String typeName) {
return TypeEntity.buildInType.getRawName().uniqName().equals(typeName) ||
builtInType.contains(typeName)||
isBuiltInTypePrefix(typeName);
}
/**
* To determine a typeName is a built-in type based on prefix.
* For example, in Java language, name start with java.*, javax.*, com.sun.*
* is build-in types
* @param typeName
* @return
*/
private boolean isBuiltInTypePrefix(String typeName) {
for (String prefix:builtInPrefix) {
if (typeName.startsWith(prefix)) return true;
}
return false;
}
/**
* In some language, there are common methods, like in ruby,
* object_id is a method for all type
* @param name
* @return
*/
public boolean isBuildInMethod(String name) {
return builtInMethod.contains(name);
}
/**
* Used by duck typing deduce feature:
* - if all calls of a type are build in method,
* then no duck typing is deduced
* Refer to Python built-in type for example
*
* @param functionCalls
* @return
*/
public boolean isBuildInTypeMethods(List<FunctionCall> functionCalls) {
return false;
}
}
| 3,266 | 28.432432 | 78 |
java
|
depends
|
depends-master/src/main/java/depends/entity/repo/EntityRepo.java
|
/*
MIT License
Copyright (c) 2018-2019 Gang ZHANG
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package depends.entity.repo;
import depends.entity.Entity;
import depends.entity.FileEntity;
import depends.entity.GenericName;
import java.util.Collection;
import java.util.Iterator;
public interface EntityRepo extends IdGenerator {
public static final String GLOBAL_SCOPE_NAME = "::GLOBAL::";
Entity getEntity(String entityName);
Entity getEntity(Integer entityId);
Entity getEntity(GenericName rawName);
void add(Entity entity);
Iterator<Entity> entityIterator();
void update(Entity entity);
Collection<Entity> getFileEntities();
Iterator<Entity> sortedFileIterator();
void clear();
FileEntity getFileEntity(String fileFullPath);
void completeFile(String fileFullPath);
}
| 1,783 | 29.237288 | 78 |
java
|
depends
|
depends-master/src/main/java/depends/entity/repo/SimpleIdGenerator.java
|
package depends.entity.repo;
public class SimpleIdGenerator implements IdGenerator {
private int nextAvaliableIndex;
public SimpleIdGenerator() {
nextAvaliableIndex = 0;
}
/**
* Generate a global unique ID for entity
* @return the unique id
*/
@Override
public Integer generateId() {
return nextAvaliableIndex++;
}
}
| 337 | 16.789474 | 55 |
java
|
depends
|
depends-master/src/main/java/depends/entity/repo/InMemoryEntityRepo.java
|
package depends.entity.repo;
import depends.entity.*;
import multilang.depends.util.file.FileUtil;
import java.util.*;
import java.util.Map.Entry;
public class InMemoryEntityRepo extends SimpleIdGenerator implements EntityRepo {
public class EntityMapIterator implements Iterator<Entity>{
private Iterator<Entry<Integer, Entity>> entryIterator;
public EntityMapIterator(Set<Entry<Integer, Entity>> entries) {
this.entryIterator = entries.iterator();
}
@Override
public boolean hasNext() {
return entryIterator.hasNext();
}
@Override
public Entity next() {
return entryIterator.next().getValue();
}
}
private Map<String, Entity> allEntieisByName;
private Map<Integer, Entity> allEntitiesById;
private List<Entity> allFileEntitiesByOrder;
public InMemoryEntityRepo() {
allEntieisByName = new TreeMap<>();
allEntitiesById = new TreeMap<>();
allFileEntitiesByOrder = new LinkedList<>();
add(TypeEntity.buildInType);
}
@Override
public Entity getEntity(String entityName) {
return allEntieisByName.get(entityName);
}
@Override
public Entity getEntity(Integer entityId) {
return allEntitiesById.get(entityId);
}
@Override
public void add(Entity entity) {
allEntitiesById.put(entity.getId(), entity);
String name = entity.getRawName().uniqName();
if (entity.getQualifiedName() != null && !(entity.getQualifiedName().isEmpty())) {
name = entity.getQualifiedName();
}
if (allEntieisByName.containsKey(name)) {
Entity existedEntity = allEntieisByName.get(name);
if (existedEntity instanceof MultiDeclareEntities) {
((MultiDeclareEntities) existedEntity).add(entity);
} else {
MultiDeclareEntities eMultiDeclare = new MultiDeclareEntities(existedEntity, this.generateId());
eMultiDeclare.add(entity);
allEntieisByName.put(name, eMultiDeclare);
}
} else {
allEntieisByName.put(name, entity);
}
if (entity.getParent() != null)
Entity.setParent(entity, entity.getParent());
}
@Override
public Iterator<Entity> entityIterator() {
return new EntityMapIterator(allEntitiesById.entrySet());
}
@Override
public void update(Entity entity) {
}
@Override
public Entity getEntity(GenericName rawName) {
return this.getEntity(rawName.uniqName());
}
@Override
public Collection<Entity> getFileEntities() {
return allFileEntitiesByOrder;
}
@Override
public Iterator<Entity> sortedFileIterator() {
return allFileEntitiesByOrder.iterator();
}
@Override
public void clear() {
allEntieisByName.clear();
allEntitiesById.clear();
allFileEntitiesByOrder.clear();
}
@Override
public FileEntity getFileEntity(String fileFullPath) {
fileFullPath = FileUtil.uniqFilePath(fileFullPath);
Entity entity = this.getEntity(fileFullPath);
if (entity ==null) return null;
if (entity instanceof FileEntity) return (FileEntity) entity;
if (entity instanceof MultiDeclareEntities){
MultiDeclareEntities multiDeclare = (MultiDeclareEntities) entity;
for (Entity theEntity: multiDeclare.getEntities()){
if (theEntity instanceof FileEntity){
return (FileEntity) theEntity;
}
}
}
return null;
}
@Override
public void completeFile(String fileFullPath) {
FileEntity fileEntity = getFileEntity(fileFullPath);
// in case of parse error(throw exception), the file entity may not exists
if (fileEntity!=null) {
fileEntity.cacheAllExpressions();
allFileEntitiesByOrder.add(fileEntity);
}
}
}
| 3,457 | 24.80597 | 100 |
java
|
depends
|
depends-master/src/main/java/depends/matrix/core/DependencyValue.java
|
/*
MIT License
Copyright (c) 2018-2019 Gang ZHANG
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package depends.matrix.core;
import java.util.ArrayList;
import java.util.List;
public class DependencyValue{
private int weight;
private String type;
private List<DependencyDetail> dependencyDetail;
public DependencyValue(String type) {
this.type = type;
this.weight=0;
dependencyDetail = new ArrayList<>();
}
public void addDependency(int weight, DependencyDetail detail) {
this.weight += weight;
if (detail!=null)
dependencyDetail.add(detail);
}
public int getWeight() {
return weight;
}
public String getType() {
return type;
}
public List<DependencyDetail> getDetails() {
return dependencyDetail;
}
public void addDependency(int weight, List<DependencyDetail> details) {
this.weight += weight;
if (details!=null)
dependencyDetail.addAll(details);
}
}
| 1,923 | 29.0625 | 78 |
java
|
depends
|
depends-master/src/main/java/depends/matrix/core/DependencyDetail.java
|
package depends.matrix.core;
public class DependencyDetail {
private LocationInfo from;
private LocationInfo to;
public DependencyDetail(LocationInfo from, LocationInfo to) {
this.from = from;
this.to = to;
}
@Override
public String toString() {
return from + "->" + to;
}
public LocationInfo getSrc() {
return from;
}
public LocationInfo getDest() {
return to;
}
}
| 392 | 14.72 | 62 |
java
|
depends
|
depends-master/src/main/java/depends/matrix/core/DependencyPair.java
|
/*
MIT License
Copyright (c) 2018-2019 Gang ZHANG
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package depends.matrix.core;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
public class DependencyPair {
private Integer from;
private Integer to;
HashMap<String, DependencyValue> dependencies;
public DependencyPair(Integer from, Integer to) {
this.from = from;
this.to= to;
dependencies = new HashMap<>();
}
public static String key(Integer from, Integer to) {
return ""+from+"-->"+to;
}
public void addDependency(String depType, int weight, DependencyDetail detail) {
if (dependencies.get(depType)==null)
dependencies.put(depType, new DependencyValue(depType));
DependencyValue value = dependencies.get(depType);
value.addDependency(weight,detail);
}
public void addDependency(String depType, int weight, List<DependencyDetail> details) {
if (dependencies.get(depType)==null)
dependencies.put(depType, new DependencyValue(depType));
DependencyValue value = dependencies.get(depType);
value.addDependency(weight,details);
}
public Integer getFrom() {
return from;
}
public Integer getTo() {
return to;
}
public Collection<DependencyValue> getDependencies() {
return dependencies.values();
}
public void reMap(Integer from, Integer to) {
this.from = from;
this.to = to;
}
}
| 2,352 | 30.797297 | 88 |
java
|
depends
|
depends-master/src/main/java/depends/matrix/core/LocationInfo.java
|
package depends.matrix.core;
import java.io.Serializable;
public class LocationInfo implements Serializable {
String object;
String file;
String type;
Integer lineNumber;
public LocationInfo(String object, String type, String file, Integer lineNumber){
if (lineNumber ==null) lineNumber = 0;
this.object = object;
this.file = file;
this.lineNumber = lineNumber;
this.type = type;
}
public String getObject() {
return object;
}
public String getFile() {
return file;
}
public String getType() {
return type;
}
public Integer getLineNumber() {
return lineNumber;
}
@Override
public String toString(){
return object + "<" + type +">" + "(" + file + ":"+ lineNumber +")";
}
}
| 715 | 17.842105 | 82 |
java
|
depends
|
depends-master/src/main/java/depends/matrix/core/DependencyMatrix.java
|
/*
MIT License
Copyright (c) 2018-2019 Gang ZHANG
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package depends.matrix.core;
import multilang.depends.util.file.path.FilenameWritter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import static depends.deptypes.DependencyType.POSSIBLE_DEP;
public class DependencyMatrix {
private final boolean outputSelfDependencies;
private HashMap<String, DependencyPair> dependencyPairs = new HashMap<>();
private ArrayList<String> nodes = new ArrayList<>();
private HashMap<Integer,String> nodeIdToName = new HashMap<>();
private List<String> typeFilter;
public DependencyMatrix(int size, List<String> typeFilter,boolean outputSelfDependencies) {
dependencyPairs = new HashMap<>(size);
this.typeFilter = typeFilter;
this.outputSelfDependencies = outputSelfDependencies;
}
public Collection<DependencyPair> getDependencyPairs() {
return dependencyPairs.values();
}
public void addNode(String name, int id) {
this.nodes.add(name);
this.nodeIdToName.put(id, name);
}
public void addDependency(String depType, Integer from, Integer to, int weight,List<DependencyDetail> details) {
if (typeFilter!=null && (!typeFilter.contains(depType)))
return;
if (!outputSelfDependencies && from.equals(to) ){
return;
}
if( from == -1 || to == -1) {
return;
}
if (dependencyPairs.get(DependencyPair.key(from,to))==null) {
dependencyPairs.put(DependencyPair.key(from,to),new DependencyPair(from,to));
}
DependencyPair dependencyPair = dependencyPairs.get(DependencyPair.key(from,to));
dependencyPair.addDependency(depType,weight,details);
}
public void addDependency(String depType, Integer from, Integer to, int weight,DependencyDetail detail) {
if (typeFilter!=null && (!typeFilter.contains(depType.replace(POSSIBLE_DEP,""))))
return;
if (!outputSelfDependencies && from.equals(to) ){
return;
}
if( from == -1 || to == -1) {
return;
}
if (dependencyPairs.get(DependencyPair.key(from,to))==null) {
dependencyPairs.put(DependencyPair.key(from,to),new DependencyPair(from,to));
}
DependencyPair dependencyPair = dependencyPairs.get(DependencyPair.key(from,to));
dependencyPair.addDependency(depType,weight,detail);
}
public ArrayList<String> getNodes() {
return nodes;
}
public DependencyMatrix reWriteFilenamePattern(FilenameWritter filenameRewritter) {
this.nodeIdToName = new HashMap<>();
for (int i=0;i<nodes.size();i++) {
String name = filenameRewritter.reWrite(nodes.get(i));
nodes.set(i, name );
nodeIdToName.put(i, name);
}
return this;
}
public String getNodeName(Integer key) {
return nodeIdToName.get(key);
}
public boolean isOutputSelfDependencies(){
return outputSelfDependencies;
}
}
| 3,817 | 32.787611 | 114 |
java
|
depends
|
depends-master/src/main/java/depends/matrix/transform/MatrixLevelReducer.java
|
/*
MIT License
Copyright (c) 2018-2019 Gang ZHANG
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package depends.matrix.transform;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import depends.matrix.core.DependencyMatrix;
import depends.matrix.core.DependencyPair;
import depends.matrix.core.DependencyValue;
public class MatrixLevelReducer {
private DependencyMatrix origin;
private int level;
HashMap<String, Integer> nodesMap = new HashMap<>();
public MatrixLevelReducer(DependencyMatrix matrix, String levelString) {
this.origin = matrix;
this.level = stringToPositiveInt(levelString);
}
public DependencyMatrix shrinkToLevel() {
if (level < 0)
return origin;
ArrayList<String> reMappedNodes = new ArrayList<>();
for (String node : origin.getNodes()) {
String newNode = calcuateNodeAtLevel(node, level);
if (!reMappedNodes.contains(newNode)) {
reMappedNodes.add(newNode);
}
}
// sort nodes by name
reMappedNodes.sort(new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
return o1.compareTo(o2);
}
});
DependencyMatrix ordered = new DependencyMatrix(0,null,false);
for (int id=0;id<reMappedNodes.size();id++) {
nodesMap.put(reMappedNodes.get(id), id);
ordered.addNode(reMappedNodes.get(id), id);
}
// add dependencies
for (DependencyPair dependencyPair : origin.getDependencyPairs()) {
for (DependencyValue dep : dependencyPair.getDependencies()) {
ordered.addDependency(dep.getType(), translateToNewId(dependencyPair.getFrom()),
translateToNewId(dependencyPair.getTo()), dep.getWeight(), dep.getDetails());
}
}
return ordered;
}
public static String calcuateNodeAtLevel(String node, int level) {
String splitterRegex = "\\.";
String splitter = ".";
String windowsSplitter = "\\";
String unixSplitter = "/";
if (node.contains(windowsSplitter)) {
splitter = windowsSplitter;
splitterRegex = windowsSplitter+windowsSplitter;
}else if (node.contains(unixSplitter)) {
splitter = unixSplitter;
splitterRegex = unixSplitter;
}
String prefix = "";
if (node.startsWith(splitter)) {
prefix = splitter;
}
String[] segments = node.split(splitterRegex);
StringBuffer sb = new StringBuffer();
int count = 0;
for (int i = 0; i < segments.length; i++) {
if (count == level)
break;
if (segments[i].length() > 0) {
if (sb.length()>0)
sb.append(splitter);
sb.append(segments[i]);
count++;
}
}
return prefix + sb.toString();
}
private Integer translateToNewId(Integer id) {
String newNode = calcuateNodeAtLevel(origin.getNodeName(id), level);
return nodesMap.get(newNode);
}
private int stringToPositiveInt(String level) {
int result = -1;
try {
result = Integer.parseInt(level);
} catch (Exception e) {
result = -1;
}
if (result <= 0) {
result = -1;
}
return result;
}
}
| 3,922 | 28.719697 | 84 |
java
|
depends
|
depends-master/src/main/java/depends/matrix/transform/OrderedMatrixGenerator.java
|
package depends.matrix.transform;
/*
MIT License
Copyright (c) 2018-2019 Gang ZHANG
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
import depends.matrix.core.DependencyMatrix;
import depends.matrix.core.DependencyPair;
import depends.matrix.core.DependencyValue;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
public class OrderedMatrixGenerator {
private DependencyMatrix matrix;
public OrderedMatrixGenerator(DependencyMatrix matrix) {
this.matrix = matrix;
}
public DependencyMatrix build() {
ArrayList<String> reMappedNodes= new ArrayList<>(matrix.getNodes());
//sort nodes by name
reMappedNodes.sort(new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
return o1.compareTo(o2);
}
});
DependencyMatrix ordered = new DependencyMatrix((int)(matrix.getDependencyPairs().size()/0.75+1),null,matrix.isOutputSelfDependencies());
HashMap<String, Integer> nodesMap = new HashMap<>();
for (int id=0;id<reMappedNodes.size();id++) {
nodesMap.put(reMappedNodes.get(id), id);
ordered.addNode(reMappedNodes.get(id), id);
}
//add dependencies
for (DependencyPair dependencyPair:matrix.getDependencyPairs()) {
Integer from = dependencyPair.getFrom();
Integer to = dependencyPair.getTo();
for (DependencyValue dep:dependencyPair.getDependencies()) {
ordered.addDependency(dep.getType(), translateToNewId( nodesMap, from), translateToNewId( nodesMap, to), dep.getWeight(),dep.getDetails());
}
}
return ordered;
}
private Integer translateToNewId( HashMap<String, Integer> nodesMap, Integer id) {
return nodesMap.get(matrix.getNodeName(id));
}
}
| 2,669 | 36.605634 | 143 |
java
|
depends
|
depends-master/src/main/java/depends/deptypes/DependencyType.java
|
/*
MIT License
Copyright (c) 2018-2019 Gang ZHANG
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package depends.deptypes;
import java.util.ArrayList;
public class DependencyType {
public static final String IMPORT = "Import";
public static final String CONTAIN = "Contain";
public static final String IMPLEMENT = "Implement";
public static final String INHERIT = "Extend";
public static final String CALL = "Call";
public static final String PARAMETER = "Parameter";
public static final String RETURN = "Return";
public static final String SET = "Set";
public static final String USE = "Use";
public static final String RECEIVE = "Receive";
public static final String CREATE = "Create";
public static final String CAST = "Cast";
public static final String THROW = "Throw";
public static final String LINK = "Link";
public static final String ANNOTATION = "Annotation";
public static final String MIXIN = "MixIn";
public static final String PomParent = "Parent";
public static final String PomPlugin = "Plugin";
public static final String PomDependency = "Dependency";
public static final String POSSIBLE_DEP = "(possible)";
public static ArrayList<String> allDependencies() {
ArrayList<String> depedencyTypes = new ArrayList<String>();
depedencyTypes.add(IMPORT);
depedencyTypes.add(CONTAIN);
depedencyTypes.add(IMPLEMENT);
depedencyTypes.add(INHERIT);
depedencyTypes.add(CALL);
depedencyTypes.add(PARAMETER);
depedencyTypes.add(RETURN);
depedencyTypes.add(SET);
depedencyTypes.add(CREATE);
depedencyTypes.add(USE);
depedencyTypes.add(RECEIVE);
depedencyTypes.add(CAST);
depedencyTypes.add(THROW);
depedencyTypes.add(ANNOTATION);
depedencyTypes.add(MIXIN);
depedencyTypes.add(LINK);
depedencyTypes.add(PomParent);
depedencyTypes.add(PomPlugin);
depedencyTypes.add(PomDependency);
return depedencyTypes;
}
}
| 2,858 | 36.618421 | 78 |
java
|
depends
|
depends-master/src/main/java/depends/importtypes/FileImport.java
|
/*
MIT License
Copyright (c) 2018-2019 Gang ZHANG
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package depends.importtypes;
public class FileImport extends Import{
public FileImport(String content) {
super(content);
}
}
| 1,209 | 36.8125 | 78 |
java
|
depends
|
depends-master/src/main/java/depends/importtypes/PackageWildCardImport.java
|
/*
MIT License
Copyright (c) 2018-2019 Gang ZHANG
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package depends.importtypes;
public class PackageWildCardImport extends Import{
public PackageWildCardImport(String content) {
super(content);
}
}
| 1,231 | 37.5 | 78 |
java
|
depends
|
depends-master/src/main/java/depends/importtypes/ExactMatchImport.java
|
/*
MIT License
Copyright (c) 2018-2019 Gang ZHANG
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package depends.importtypes;
public class ExactMatchImport extends Import{
public ExactMatchImport(String content) {
super(content);
}
}
| 1,221 | 37.1875 | 78 |
java
|
depends
|
depends-master/src/main/java/depends/importtypes/Import.java
|
/*
MIT License
Copyright (c) 2018-2019 Gang ZHANG
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package depends.importtypes;
public abstract class Import {
private String content;
public String getContent() {
return content;
}
public Import(String content) {
this.content = content;
}
public void setContent(String content) {
this.content = content;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((content == null) ? 0 : content.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Import other = (Import) obj;
if (content == null) {
if (other.content != null)
return false;
} else if (!content.equals(other.content))
return false;
return true;
}
}
| 1,881 | 28.40625 | 78 |
java
|
depends
|
depends-master/src/main/java/depends/relations/FunctionMatcher.java
|
/*
MIT License
Copyright (c) 2018-2019 Gang ZHANG
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package depends.relations;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import depends.entity.FunctionCall;
import depends.entity.FunctionEntity;
import depends.entity.GenericName;
public class FunctionMatcher {
private HashSet<GenericName> fnames;
public FunctionMatcher(ArrayList<FunctionEntity> functions) {
fnames = new HashSet<>();
for (FunctionEntity f:functions) {
this.fnames.add(f.getRawName());
}
}
public boolean containsAll(List<FunctionCall> functionCalls) {
for (FunctionCall fCall:functionCalls) {
if (!fnames.contains(fCall.getRawName()))
return false;
}
return true;
}
}
| 1,732 | 31.092593 | 78 |
java
|
depends
|
depends-master/src/main/java/depends/relations/Relation.java
|
/*
MIT License
Copyright (c) 2018-2019 Gang ZHANG
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package depends.relations;
import depends.entity.Entity;
import depends.entity.Location;
/**
* Dependency relation object
*/
public class Relation {
/*Where the relation happen in src*/
private Location location;
private String type;
private Entity toEntity;
private boolean possibleDependency;
public Relation(String type, Entity toEntity,Location location, boolean possibleDependency) {
this.toEntity = toEntity;
this.type = type;
this.location = location;
this.possibleDependency = possibleDependency;
}
public String getType() {
return type;
}
@Override
public String toString() {
return "Relation[" + type + "]-->" + toEntity.getId() + "(" + toEntity.getQualifiedName() + ")";
}
public Entity getEntity() {
return toEntity;
}
public Integer getFromLine() {
if (location==null) return null;
return location.getLine();
}
public boolean possible() {
return this.possibleDependency;
}
}
| 2,014 | 29.074627 | 98 |
java
|
depends
|
depends-master/src/main/java/depends/relations/BindingResolver.java
|
/*
MIT License
Copyright (c) 2018-2019 Gang ZHANG
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package depends.relations;
import depends.entity.*;
import depends.entity.repo.BuiltInType;
import depends.entity.repo.EntityRepo;
import depends.extractor.AbstractLangProcessor;
import depends.extractor.UnsolvedBindings;
import depends.extractor.empty.EmptyBuiltInType;
import depends.importtypes.Import;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.management.ManagementFactory;
import java.util.*;
public class BindingResolver implements IBindingResolver{
private BuiltInType buildInTypeManager = new EmptyBuiltInType();
private ImportLookupStrategy importLookupStrategy;
private Set<UnsolvedBindings> unsolvedSymbols = new HashSet<>();
private EntityRepo repo;
private boolean eagerExpressionResolve = false;
private boolean isCollectUnsolvedBindings = false;
private boolean isDuckTypingDeduce = true;
private static Logger logger = LoggerFactory.getLogger(IBindingResolver.class);
public BindingResolver(AbstractLangProcessor langProcessor,
boolean isCollectUnsolvedBindings, boolean isDuckTypingDeduce) {
this.repo = langProcessor.getEntityRepo();
this.importLookupStrategy = langProcessor.getImportLookupStrategy();
this.buildInTypeManager = langProcessor.getBuiltInType();
this.isCollectUnsolvedBindings = isCollectUnsolvedBindings;
this.isDuckTypingDeduce = isDuckTypingDeduce;
unsolvedSymbols= new HashSet<>();
importLookupStrategy.setBindingResolver(this);
}
@Override
public Set<UnsolvedBindings> resolveAllBindings(boolean isEagerExpressionResolve) {
System.out.println("Resolve type bindings....");
if (logger.isInfoEnabled()) {
logger.info("Resolve type bindings...");
}
resolveTypes(isEagerExpressionResolve);
System.out.println("Dependency analaysing....");
if (logger.isInfoEnabled()) {
logger.info("Dependency analaysing...");
}
logger.info("Heap Information: " + ManagementFactory.getMemoryMXBean().getHeapMemoryUsage());
return unsolvedSymbols;
}
private void resolveTypes(boolean eagerExpressionResolve) {
this.eagerExpressionResolve = eagerExpressionResolve;
Iterator<Entity> iterator = repo.sortedFileIterator();
while(iterator.hasNext()) {
Entity entity= iterator.next();
entity.inferEntities(this);
}
}
@Override
public Collection<Entity> getImportedRelationEntities(List<Import> importedNames) {
return importLookupStrategy.getImportedRelationEntities(importedNames);
}
@Override
public Collection<Entity> getImportedTypes(List<Import> importedNames, FileEntity fileEntity) {
HashSet<UnsolvedBindings> unsolved = new HashSet<UnsolvedBindings>();
Collection<Entity> result = importLookupStrategy.getImportedTypes(importedNames,unsolved);
for (UnsolvedBindings item:unsolved) {
item.setFromEntity(fileEntity);
addUnsolvedBinding(item);
}
return result;
}
private void addUnsolvedBinding(UnsolvedBindings item) {
if (!isCollectUnsolvedBindings) return;
this.unsolvedSymbols.add(item);
}
@Override
public Collection<Entity> getImportedFiles(List<Import> importedNames) {
return importLookupStrategy.getImportedFiles(importedNames);
}
@Override
public TypeEntity inferTypeFromName(Entity fromEntity, GenericName rawName) {
Entity data = resolveName(fromEntity, rawName, true);
if (data == null)
return null;
return data.getType();
}
@Override
public Entity resolveName(Entity fromEntity, GenericName rawName, boolean searchImport) {
if (rawName==null) return null;
Entity entity = resolveNameInternal(fromEntity,rawName,searchImport);
if (entity==null ) {
if (!this.buildInTypeManager.isBuiltInType(rawName.getName())) {
addUnsolvedBinding(new UnsolvedBindings(rawName.getName(), fromEntity));
}
}
return entity;
}
private Entity resolveNameInternal(Entity fromEntity, GenericName rawName, boolean searchImport) {
if (rawName==null || rawName.getName()==null)
return null;
if (buildInTypeManager.isBuiltInType(rawName.getName())) {
return TypeEntity.buildInType;
}
// qualified name will first try global name directly
if (rawName.startsWith(".")) {
rawName = rawName.substring(1);
if (repo.getEntity(rawName) != null)
return repo.getEntity(rawName);
}
Entity entity = null;
int indexCount = 0;
String name = rawName.getName();
if (fromEntity==null) return null;
do {
entity = lookupEntity(fromEntity, name, searchImport);
if (entity!=null ) {
break;
}
if (importLookupStrategy.supportGlobalNameLookup()) {
if (repo.getEntity(name) != null) {
entity = repo.getEntity(name);
break;
}
}
indexCount++;
if (name.contains("."))
name = name.substring(0,name.lastIndexOf('.'));
else
break;
}while (true);
if (entity == null) {
return null;
}
String[] names = rawName.getName().split("\\.");
if (names.length == 0)
return null;
if (names.length == 1) {
return entity;
}
// then find the subsequent symbols
return findEntitySince(entity, names, names.length-indexCount);
}
private Entity lookupEntity(Entity fromEntity, String name, boolean searchImport) {
if (name.equals("this") || name.equals("class") ) {
TypeEntity entityType = (TypeEntity) (fromEntity.getAncestorOfType(TypeEntity.class));
return entityType;
} else if (name.equals("super")) {
TypeEntity parent = (TypeEntity) (fromEntity.getAncestorOfType(TypeEntity.class));
if (parent != null) {
TypeEntity parentType = parent.getInheritedType();
if (parentType!=null)
return parentType;
}
}
Entity inferData = findEntityUnderSamePackage(fromEntity, name);
if (inferData != null) {
return inferData;
}
if (searchImport)
inferData = lookupTypeInImported((FileEntity)(fromEntity.getAncestorOfType(FileEntity.class)), name);
return inferData;
}
/**
* To lookup entity in case of a.b.c from a;
* @param precendenceEntity
* @param names
* @param nameIndex
* @return
*/
private Entity findEntitySince(Entity precendenceEntity, String[] names, int nameIndex) {
if (nameIndex >= names.length) {
return precendenceEntity;
}
if (nameIndex == -1) {
System.err.println("No expected symbols: names"+Arrays.toString(names) +", index=" + nameIndex);
return null;
}
//If it is not an entity with types (not a type, var, function), fall back to itself
if (precendenceEntity.getType()==null)
return precendenceEntity;
for (Entity child : precendenceEntity.getType().getChildren()) {
if (child.getRawName().getName().equals(names[nameIndex])) {
return findEntitySince(child, names, nameIndex + 1);
}
}
return null;
}
@Override
public Entity lookupTypeInImported(FileEntity fileEntity, String name) {
if (fileEntity == null)
return null;
Entity type = importLookupStrategy.lookupImportedType(name, fileEntity);
if (type != null)
return type;
return null;
}
/**
* In Java/C++ etc, the same package names should take priority of resolving.
* the entity lookup is implemented recursively.
* @param fromEntity
* @param name
* @return
*/
private Entity findEntityUnderSamePackage(Entity fromEntity, String name) {
while (true) {
Entity entity = fromEntity.getByName(name, new HashSet<>());
if (entity!=null) return entity;
fromEntity = fromEntity.getParent();
if (fromEntity == null)
break;
}
return null;
}
@Override
public List<TypeEntity> calculateCandidateTypes(VarEntity fromEntity, List<FunctionCall> functionCalls) {
if (buildInTypeManager.isBuildInTypeMethods(functionCalls)) {
return new ArrayList<>();
}
if (!isDuckTypingDeduce)
return new ArrayList<>();
return searchTypesInRepo(fromEntity, functionCalls);
}
private List<TypeEntity> searchTypesInRepo(VarEntity fromEntity, List<FunctionCall> functionCalls) {
List<TypeEntity> types = new ArrayList<>();
Iterator<Entity> iterator = repo.sortedFileIterator();
while(iterator.hasNext()) {
Entity f = iterator.next();
if (f instanceof FileEntity) {
for (TypeEntity type:((FileEntity)f).getDeclaredTypes()) {
FunctionMatcher functionMatcher = new FunctionMatcher(type.getFunctions());
if (functionMatcher.containsAll(functionCalls)) {
types.add(type);
}
}
}
}
return types;
}
@Override
public boolean isEagerExpressionResolve() {
return eagerExpressionResolve;
}
@Override
public EntityRepo getRepo() {
return repo;
}
}
| 9,481 | 30.818792 | 106 |
java
|
depends
|
depends-master/src/main/java/depends/relations/ImportLookupStrategy.java
|
/*
MIT License
Copyright (c) 2018-2019 Gang ZHANG
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package depends.relations;
import depends.entity.Entity;
import depends.entity.FileEntity;
import depends.entity.repo.EntityRepo;
import depends.extractor.UnsolvedBindings;
import depends.importtypes.Import;
import java.util.Collection;
import java.util.List;
import java.util.Set;
public abstract class ImportLookupStrategy {
/**
* How to find the corresponding entity out of current scope
*
* @param name - the entity name
* @param fileEntity - the current file
* @return the founded entity, or null if not found.
*/
public abstract Entity lookupImportedType(String name, FileEntity fileEntity);
/**
* The lanaguage specific import relation computation. For example,
* In C/CPP, it is calculated by the file name
* In Java, it is calculated by the imported types
* @param importedNames - the original name of the import relation
* @return the corresponding entities related with importedNames
*/
public abstract Collection<Entity> getImportedRelationEntities(List<Import> importedNames);
/**
* The types been imported
* @param importedNames
* @return
*/
public abstract Collection<Entity> getImportedTypes(List<Import> importedNames,Set<UnsolvedBindings> unsolvedSymbols);
/**
* The files been imported
* @param importedNames
* @return
*/
public abstract Collection<Entity> getImportedFiles(List<Import> importedNames);
/** Whether support global name lookup
* for java, it should be true;
* for most of langs, it should be false;
*/
public abstract boolean supportGlobalNameLookup();
public void setBindingResolver(IBindingResolver bindingResolver){
this.bindingResolver = bindingResolver;
}
public ImportLookupStrategy(EntityRepo repo){
this.repo = repo;
}
protected EntityRepo repo;
protected IBindingResolver bindingResolver;
}
| 2,893 | 33.047059 | 119 |
java
|
depends
|
depends-master/src/main/java/depends/relations/RelationCounter.java
|
/*
MIT License
Copyright (c) 2018-2019 Gang ZHANG
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package depends.relations;
import depends.deptypes.DependencyType;
import depends.entity.*;
import depends.entity.repo.EntityRepo;
import depends.extractor.AbstractLangProcessor;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;
public class RelationCounter {
private Collection<Entity> entities;
private IBindingResolver bindingResolver;
private EntityRepo repo;
private boolean callAsImpl;
private AbstractLangProcessor langProcessor;
public RelationCounter(EntityRepo repo, AbstractLangProcessor langProcessor, IBindingResolver bindingResolver) {
this.entities = repo.getFileEntities();
this.bindingResolver = bindingResolver;
this.repo = repo;
this.callAsImpl = langProcessor.supportCallAsImpl();
this.langProcessor = langProcessor;
}
public void computeRelations() {
entities.forEach(entity->
computeRelationOf(entity));
}
private void computeRelationOf(Entity entity) {
if (!entity.inScope())
return;
if (entity instanceof FileEntity) {
computeImports((FileEntity)entity);
}
else if (entity instanceof FunctionEntity) {
computeFunctionRelations((FunctionEntity)entity);
}
else if (entity instanceof TypeEntity) {
computeTypeRelations((TypeEntity)entity);
}
if (entity instanceof ContainerEntity) {
computeContainerRelations((ContainerEntity)entity);
}
entity.getChildren().forEach(child->computeRelationOf(child));
}
private void computeContainerRelations(ContainerEntity entity) {
for (VarEntity var:entity.getVars()) {
if (var.getType()!=null)
entity.addRelation(buildRelation(entity,DependencyType.CONTAIN,var.getType(),var.getLocation()));
for (Entity type:var.getResolvedTypeParameters()) {
var.addRelation(buildRelation(var, DependencyType.PARAMETER,type));
}
}
for (Entity type:entity.getResolvedAnnotations()) {
entity.addRelation(buildRelation(entity,DependencyType.ANNOTATION,type));
}
for (Entity type:entity.getResolvedTypeParameters()) {
entity.addRelation(buildRelation(entity,DependencyType.USE,type));
}
for (ContainerEntity mixin:entity.getResolvedMixins()) {
entity.addRelation(buildRelation(entity,DependencyType.MIXIN,mixin));
}
entity.reloadExpression(repo);
if (!bindingResolver.isEagerExpressionResolve())
{
entity.resolveExpressions(bindingResolver);
}
for (Expression expression:entity.expressionList()){
if (expression.isStatement()) {
continue;
}
Entity referredEntity = expression.getReferredEntity();
addRelationFromExpression(entity, expression, referredEntity, false);
}
entity.clearExpressions();
}
private void addRelationFromExpression(ContainerEntity entity, Expression expression, Entity referredEntity, boolean possibleDependency) {
if (referredEntity==null) {
return;
}
if (referredEntity.getId()<0){
return;
}
if (referredEntity instanceof MultiDeclareEntities) {
for (Entity e:((MultiDeclareEntities)referredEntity).getEntities()) {
addRelationFromExpression(entity,expression,e, true);
}
return;
}
boolean matched = false;
if (expression.isCall()) {
/* if it is a FunctionEntityProto, add Relation to all Impl Entities*/
if (callAsImpl && referredEntity instanceof FunctionEntityProto) {
if (entity.getAncestorOfType(FileEntity.class).getId().equals(referredEntity.getAncestorOfType(FileEntity.class).getId())){
entity.addRelation(buildRelation(entity,DependencyType.CALL,referredEntity,expression.getLocation(), possibleDependency));
}else {
Entity multiDeclare = repo.getEntity(referredEntity.getQualifiedName());
if (multiDeclare instanceof MultiDeclareEntities) {
MultiDeclareEntities m = (MultiDeclareEntities) multiDeclare;
List<Entity> entities = m.getEntities().stream().filter(item -> (item instanceof FunctionEntityImpl))
.collect(Collectors.toList());
for (Entity e : entities) {
entity.addRelation(expression, buildRelation(entity, DependencyType.LINK, e, expression.getLocation(), true));
matched = true;
}
}
}
}
entity.addRelation(buildRelation(entity,DependencyType.CALL,referredEntity,expression.getLocation(), possibleDependency));
matched = true;
}
if (expression.isCreate()) {
entity.addRelation(buildRelation(entity,DependencyType.CREATE,referredEntity,expression.getLocation(), possibleDependency));
matched = true;
}
if (expression.isThrow()) {
entity.addRelation(buildRelation(entity,DependencyType.THROW,referredEntity,expression.getLocation(), possibleDependency));
matched = true;
}
if (expression.isCast()) {
entity.addRelation(buildRelation(entity,DependencyType.CAST,referredEntity,expression.getLocation(), possibleDependency));
matched = true;
}
if (!matched) {
if (callAsImpl && repo.getEntity(referredEntity.getQualifiedName()) instanceof MultiDeclareEntities &&
(referredEntity instanceof VarEntity ||referredEntity instanceof FunctionEntity)) {
if (entity.getAncestorOfType(FileEntity.class).getId().equals(referredEntity.getAncestorOfType(FileEntity.class).getId())){
entity.addRelation(buildRelation(entity,DependencyType.USE,referredEntity,expression.getLocation(), possibleDependency));
}else {
MultiDeclareEntities m = (MultiDeclareEntities) (repo.getEntity(referredEntity.getQualifiedName()));
for (Entity e : m.getEntities()) {
if (e == referredEntity) {
entity.addRelation(expression, buildRelation(entity, DependencyType.USE, e, expression.getLocation(), true));
} else {
entity.addRelation(expression, buildRelation(entity, DependencyType.LINK, e, expression.getLocation(), true));
}
matched = true;
}
}
}
else {
entity.addRelation(expression,buildRelation(entity,DependencyType.USE,referredEntity,expression.getLocation(), possibleDependency));
}
}
}
private Relation buildRelation(Entity from, String type, Entity referredEntity, boolean possibleDependency) {
return buildRelation(from,type,referredEntity,from.getLocation(), possibleDependency);
}
private Relation buildRelation(ContainerEntity from, String type, Entity referredEntity) {
return buildRelation(from,type,referredEntity, false);
}
private Relation buildRelation(Entity from, String type, Entity referredEntity,Location location) {
return buildRelation(from,type,referredEntity, location,false);
}
private Relation buildRelation(Entity from, String type, Entity referredEntity,Location location, boolean possibleDependency) {
if (referredEntity instanceof AliasEntity) {
if (from.getAncestorOfType(FileEntity.class).equals(referredEntity.getAncestorOfType(FileEntity.class))) {
AliasEntity alias = ((AliasEntity) referredEntity);
if (alias.deepResolve()!=null) {
referredEntity = alias.deepResolve();
}
}
}
if (referredEntity instanceof CandidateTypes)
possibleDependency = true;
if (this.langProcessor==null)
return new Relation(type,referredEntity,location, possibleDependency);
return new Relation(langProcessor.getRelationMapping(type),referredEntity,location, possibleDependency);
}
private void computeTypeRelations(TypeEntity type) {
for (TypeEntity superType:type.getInheritedTypes()) {
type.addRelation(buildRelation(type,DependencyType.INHERIT,superType));
}
for (TypeEntity interfaceType:type.getImplementedTypes()) {
type.addRelation(buildRelation(type,DependencyType.IMPLEMENT,interfaceType));
}
}
private void computeFunctionRelations(FunctionEntity func) {
for (Entity returnType:func.getReturnTypes()) {
func.addRelation(buildRelation(func,DependencyType.RETURN,returnType.getActualReferTo()));
}
for (VarEntity parameter:func.getParameters()) {
if (parameter.getType()!=null)
func.addRelation(buildRelation(func,DependencyType.PARAMETER,parameter.getActualReferTo()));
}
for (Entity throwType:func.getThrowTypes()) {
func.addRelation(buildRelation(func,DependencyType.THROW,throwType));
}
for (Entity type:func.getResolvedTypeParameters()) {
func.addRelation(buildRelation(func,DependencyType.PARAMETER,type));
}
if (func instanceof FunctionEntityImpl) {
FunctionEntityImpl funcImpl = (FunctionEntityImpl)func;
if(funcImpl.getImplemented()!=null) {
func.addRelation(buildRelation(func,DependencyType.IMPLEMENT,funcImpl.getImplemented()));
}
}
}
private void computeImports(FileEntity file) {
Collection<Entity> imports = file.getImportedRelationEntities();
if (imports==null) return;
for (Entity imported:imports) {
if (imported instanceof FileEntity)
{
if (((FileEntity)imported).isInProjectScope())
file.addRelation(buildRelation(file,DependencyType.IMPORT,imported));
}else {
file.addRelation(buildRelation(file,DependencyType.IMPORT,imported));
}
}
}
}
| 9,934 | 37.657588 | 139 |
java
|
depends
|
depends-master/src/main/java/depends/relations/IBindingResolver.java
|
package depends.relations;
import depends.entity.*;
import depends.entity.repo.EntityRepo;
import depends.extractor.UnsolvedBindings;
import depends.importtypes.Import;
import java.util.Collection;
import java.util.List;
import java.util.Set;
public interface IBindingResolver {
/**
* Resolve all bindings
* - Firstly, we resolve all types from there names.
* - Secondly, we resolve all expressions (expression will use type infomation of previous step
*/
Set<UnsolvedBindings> resolveAllBindings(boolean isEagerExpressionResolve);
/**
* Different languages have different strategy on how to compute the imported types
* and the imported files.
* For example, in C/C++, both imported types (using namespace, using <type>) and imported files exists.
* while in java, only 'import class/function, or import wildcard class.* package.* exists.
*/
Collection<Entity> getImportedRelationEntities(List<Import> importedNames);
Collection<Entity> getImportedTypes(List<Import> importedNames, FileEntity fileEntity);
Collection<Entity> getImportedFiles(List<Import> importedNames);
/**
* By given raw name, to infer the type of the name
* for example
* (It is just a wrapper of resolve name)
* if it is a class, the class is the type
* if it is a function, the return type is the type
* if it is a variable, type of variable is the type
* @param fromEntity
* @param rawName
* @return
*/
TypeEntity inferTypeFromName(Entity fromEntity, GenericName rawName);
/**
* By given raw name, to infer the entity of the name
* @param fromEntity
* @param rawName
* @param searchImport
* @return
*/
Entity resolveName(Entity fromEntity, GenericName rawName, boolean searchImport);
Entity lookupTypeInImported(FileEntity fileEntity, String name);
/**
* Deduce type based on function calls
* If the function call is a subset of a type, then the type could be a candidate of the var's type
* @param fromEntity
* @param functionCalls
* @return
*/
List<TypeEntity> calculateCandidateTypes(VarEntity fromEntity, List<FunctionCall> functionCalls);
boolean isEagerExpressionResolve();
EntityRepo getRepo();
}
| 2,311 | 32.507246 | 108 |
java
|
depends
|
depends-master/src/main/java/depends/generator/FunctionDependencyGenerator.java
|
/*
MIT License
Copyright (c) 2018-2019 Gang ZHANG
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package depends.generator;
import depends.entity.Entity;
import depends.entity.EntityNameBuilder;
import depends.entity.FileEntity;
import depends.entity.FunctionEntity;
import depends.entity.repo.EntityRepo;
public class FunctionDependencyGenerator extends DependencyGenerator {
@Override
protected boolean outputLevelMatch(Entity entity) {
return (entity instanceof FunctionEntity);
}
@Override
protected String nameOf(Entity entity) {
FileEntity file = (FileEntity) entity.getAncestorOfType(FileEntity.class);
String name = stripper.stripFilename(file.getRawName().uniqName());
name = filenameWritter.reWrite(name);
String functionName = EntityNameBuilder.build(entity);
functionName = stripper.stripFilename(functionName);
name = name + "("+functionName+")";
return name;
}
@Override
protected int upToOutputLevelEntityId(EntityRepo entityRepo, Entity entity) {
Entity ancestor = entity.getAncestorOfType(FunctionEntity.class);
if (ancestor == null)
return -1;
if (!ancestor.inScope()) return -1;
return ancestor.getId();
}
@Override
public String getType() {
return "method";
}
}
| 2,211 | 33.030769 | 78 |
java
|
depends
|
depends-master/src/main/java/depends/generator/StructureDependencyGenerator.java
|
/*
MIT License
Copyright (c) 2018-2019 Gang ZHANG
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package depends.generator;
import depends.entity.*;
import depends.entity.repo.EntityRepo;
public class StructureDependencyGenerator extends DependencyGenerator{
@Override
protected String nameOf(Entity entity) {
return entity.getQualifiedName() + "|" + entity.getClass().getSimpleName().replace("Entity","");
}
@Override
protected boolean outputLevelMatch(Entity entity) {
if (entity instanceof FileEntity) return false;
if (entity instanceof TypeEntity) return true; //package included
if (entity instanceof VarEntity && entity.getParent() instanceof TypeEntity) return true;
if (entity instanceof FunctionEntity) return true;
return false;
}
@Override
public String getType() {
return "structure";
}
@Override
protected int upToOutputLevelEntityId(EntityRepo entityRepo, Entity entity) {
Entity ancestor = getAncestorOfType(entity);
if (ancestor==null) {
return -1;
}
if (!ancestor.inScope()) return -1;
return ancestor.getId();
}
public Entity getAncestorOfType(Entity fromEntity) {
while(fromEntity!=null) {
if (outputLevelMatch(fromEntity))
return fromEntity;
if (fromEntity.getParent()==null) return null;
fromEntity = fromEntity.getParent();
}
return null;
}
}
| 2,315 | 31.619718 | 98 |
java
|
depends
|
depends-master/src/main/java/depends/generator/DependencyGenerator.java
|
/*
MIT License
Copyright (c) 2018-2019 Gang ZHANG
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package depends.generator;
import depends.entity.CandidateTypes;
import depends.entity.Entity;
import depends.entity.EntityNameBuilder;
import depends.entity.FileEntity;
import depends.entity.repo.EntityRepo;
import depends.matrix.core.DependencyDetail;
import depends.matrix.core.DependencyMatrix;
import depends.matrix.core.LocationInfo;
import depends.matrix.transform.OrderedMatrixGenerator;
import depends.relations.Relation;
import multilang.depends.util.file.path.EmptyFilenameWritter;
import multilang.depends.util.file.path.FilenameWritter;
import multilang.depends.util.file.strip.EmptyLeadingNameStripper;
import multilang.depends.util.file.strip.ILeadingNameStrippper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import static depends.deptypes.DependencyType.POSSIBLE_DEP;
public abstract class DependencyGenerator {
private static Logger logger = LoggerFactory.getLogger(DependencyGenerator.class);
private boolean outputSelfDependencies;
public abstract String getType();
public DependencyMatrix identifyDependencies(EntityRepo entityRepo, List<String> typeFilter) {
System.out.println("dependencie data generating...");
DependencyMatrix dependencyMatrix = build(entityRepo, typeFilter);
System.out.println("reorder dependency matrix...");
dependencyMatrix = new OrderedMatrixGenerator(dependencyMatrix).build();
System.out.println("Dependencies data generating done successfully...");
logger.info("Dependencies data generating done successfully...");
return dependencyMatrix;
}
/**
* Build the dependency matrix (without re-mapping file id)
* @param entityRepo which contains entities and relations
* @return the generated dependency matrix
*/
public DependencyMatrix build(EntityRepo entityRepo,List<String> typeFilter) {
DependencyMatrix dependencyMatrix = new DependencyMatrix(0, typeFilter,outputSelfDependencies);
Iterator<Entity> iterator = entityRepo.entityIterator();
System.out.println("Start create dependencies matrix....");
while(iterator.hasNext()) {
Entity entity = iterator.next();
if (!entity.inScope()) continue;
if (outputLevelMatch(entity)){
dependencyMatrix.addNode(nameOf(entity),entity.getId());
}
int entityFrom = upToOutputLevelEntityId(entityRepo, entity);
if (entityFrom==-1) continue;
for (Relation relation:entity.getRelations()) {
Entity relatedEntity = relation.getEntity();
if (relatedEntity==null) continue;
List<Entity> relatedEntities = expandEntity(relatedEntity);
String possibleDependencyFlag = relation.possible()? POSSIBLE_DEP :"";
relatedEntities.forEach(theEntity->{
if (theEntity.getId()>=0) {
int entityTo = upToOutputLevelEntityId(entityRepo,theEntity);
if (entityTo!=-1) {
DependencyDetail detail = buildDescription(entity, theEntity, relation.getFromLine());
detail = rewriteDetail(detail);
dependencyMatrix.addDependency(relation.getType()+possibleDependencyFlag, entityFrom,entityTo,1,detail);
}
}
});
}
}
System.out.println("Finish create dependencies matrix....");
return dependencyMatrix;
}
private List<Entity> expandEntity(Entity relatedEntity) {
List<Entity> entities = new ArrayList<>();
if (relatedEntity instanceof CandidateTypes) {
entities = Collections.unmodifiableList((List) ((CandidateTypes) relatedEntity).getCandidateTypes());
}else {
entities.add(relatedEntity);
}
return entities;
}
private DependencyDetail rewriteDetail(DependencyDetail detail) {
if (detail==null) return null;
String srcFile = filenameWritter.reWrite(
stripper.stripFilename(detail.getSrc().getFile())
);
String dstFile = filenameWritter.reWrite(
stripper.stripFilename(detail.getDest().getFile()));
return new DependencyDetail(
new LocationInfo(detail.getSrc().getObject(),
detail.getSrc().getType(),
srcFile, detail.getSrc().getLineNumber())
,
new LocationInfo(detail.getDest().getObject(),
detail.getDest().getType(),
dstFile, detail.getDest().getLineNumber()));
}
protected abstract int upToOutputLevelEntityId(EntityRepo entityRepo, Entity entity);
protected abstract String nameOf(Entity entity);
protected abstract boolean outputLevelMatch(Entity entity);
protected ILeadingNameStrippper stripper = new EmptyLeadingNameStripper();
protected FilenameWritter filenameWritter = new EmptyFilenameWritter();
private boolean generateDetail = false;
public void setLeadingStripper(ILeadingNameStrippper stripper) {
this.stripper = stripper;
}
protected DependencyDetail buildDescription(Entity fromEntity, Entity toEntity, Integer fromLineNumber) {
if (!generateDetail) return null;
String fromObject = EntityNameBuilder.build(fromEntity);
String toObject = EntityNameBuilder.build(toEntity);
Entity fromFile = fromEntity.getAncestorOfType(FileEntity.class);
Entity toFile = toEntity.getAncestorOfType(FileEntity.class);
// If the toEntity is above the file level (e.g. a package), then toFile will be null.
if (toFile == null) return null;
return new DependencyDetail(
new LocationInfo(stripper.stripFilename(fromObject),typeOf(fromEntity),stripper.stripFilename(fromFile.getQualifiedName()),fromLineNumber),
new LocationInfo(stripper.stripFilename(toObject),typeOf(toEntity),stripper.stripFilename(toFile.getQualifiedName()),toEntity.getLine()));
}
private String typeOf(Entity entity) {
return entity.getClass().getSimpleName().replace("Entity","").toLowerCase();
}
public void setFilenameRewritter(FilenameWritter filenameWritter) {
this.filenameWritter = filenameWritter;
}
public void setGenerateDetail(boolean generateDetail) {
this.generateDetail = generateDetail;
}
public void setOutputSelfDependencies(boolean outputSelfDependencies) {
this.outputSelfDependencies = outputSelfDependencies;
}
}
| 7,049 | 39.056818 | 143 |
java
|
depends
|
depends-master/src/main/java/depends/generator/FileDependencyGenerator.java
|
/*
MIT License
Copyright (c) 2018-2019 Gang ZHANG
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package depends.generator;
import depends.entity.Entity;
import depends.entity.FileEntity;
import depends.entity.repo.EntityRepo;
public class FileDependencyGenerator extends DependencyGenerator{
@Override
protected String nameOf(Entity entity) {
String name = stripper.stripFilename(entity.getDisplayName());
return filenameWritter.reWrite(name);
}
@Override
protected boolean outputLevelMatch(Entity entity) {
return (entity instanceof FileEntity);
}
@Override
public String getType() {
return "file";
}
@Override
protected int upToOutputLevelEntityId(EntityRepo entityRepo, Entity entity) {
Entity ancestor = entity.getAncestorOfType(FileEntity.class);
if (ancestor==null) {
return -1;
}
if (!ancestor.inScope()) return -1;
return ancestor.getId();
}
}
| 1,874 | 30.779661 | 78 |
java
|
depends
|
depends-master/src/main/java/depends/extractor/LangProcessorRegistration.java
|
/*
MIT License
Copyright (c) 2018-2019 Gang ZHANG
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package depends.extractor;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
/* Registration of the lang processors.
* */
public class LangProcessorRegistration {
private static LangProcessorRegistration inst = new LangProcessorRegistration();
public HashMap<String, AbstractLangProcessor> langProcessors = new HashMap<>();
public static LangProcessorRegistration getRegistry() {
return inst;
}
public AbstractLangProcessor getProcessorOf(String lang) {
return langProcessors.get(lang);
}
public void register(AbstractLangProcessor processor) {
if (getProcessorOf(processor.supportedLanguage())!=null) return;
langProcessors.put(processor.supportedLanguage(), processor);
}
public Collection<String> getLangs() {
ArrayList<String> langs = new ArrayList<>();
langProcessors.values().forEach(item->{langs.add(item.supportedLanguage());});
return langs;
}
}
| 1,995 | 37.384615 | 81 |
java
|
depends
|
depends-master/src/main/java/depends/extractor/HandlerContext.java
|
/*
MIT License
Copyright (c) 2018-2019 Gang ZHANG
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package depends.extractor;
import depends.entity.*;
import depends.entity.repo.EntityRepo;
import depends.entity.repo.IdGenerator;
import depends.importtypes.Import;
import depends.relations.IBindingResolver;
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
import java.util.stream.Collectors;
public abstract class HandlerContext {
protected EntityRepo entityRepo;
protected IdGenerator idGenerator;
protected FileEntity currentFileEntity;
protected IBindingResolver bindingResolver;
public HandlerContext(EntityRepo entityRepo, IBindingResolver bindingResolver) {
this.entityRepo = entityRepo;
this.idGenerator = entityRepo;
entityStack = new Stack<Entity>();
this.bindingResolver = bindingResolver;
}
public FileEntity startFile(boolean fileAsModule, String fileName) {
currentFileEntity = new FileEntity(fileAsModule, fileName, idGenerator.generateId(),true);
pushToStack(currentFileEntity);
addToRepo(currentFileEntity);
return currentFileEntity;
}
public TypeEntity foundNewType(GenericName name, Integer startLine) {
TypeEntity currentTypeEntity = new TypeEntity(name, this.latestValidContainer(),
idGenerator.generateId());
currentTypeEntity.setLine(startLine);
pushToStack(currentTypeEntity);
addToRepo(currentTypeEntity);
currentFileEntity.addType(currentTypeEntity);
return currentTypeEntity;
}
/**
* Tell the context object that a new type founded.
* @param name
* @param startLine
* @return
*/
public TypeEntity foundNewType(String name, Integer startLine) {
return foundNewType(GenericName.build(name),startLine);
}
public AliasEntity foundNewAlias(String aliasName, String originalName) {
if (aliasName.equals(originalName)) return null; //it is a tricky, we treat same name no different.
//indeed it is not perfect -> the right match should depends on no-bare format like "struct a" instead of "a"
AliasEntity currentTypeEntity = new AliasEntity(GenericName.build(aliasName), this.latestValidContainer(),
idGenerator.generateId(),GenericName.build(originalName) );
addToRepo(currentTypeEntity);
return currentTypeEntity;
}
public AliasEntity foundNewAlias(GenericName aliasName, Entity referToEntity) {
AliasEntity currentTypeEntity = new AliasEntity(aliasName, this.latestValidContainer(),
idGenerator.generateId(),aliasName);
currentTypeEntity.setReferToEntity(referToEntity);
addToRepo(currentTypeEntity);
return currentTypeEntity;
}
/**
* Tell the context that a new method was found.
* Do not forget to tell the context leave the method when you finish
* the process of the method
* @param methodName
* @param returnType - if no return type information avaliable, keep it as null;
* @param throwedType - if no throwed type information avaliable, keep it as empty list;
* @return the new function enity
*/
public FunctionEntity foundMethodDeclarator(String methodName, String returnType, List<String> throwedType, Integer startLine) {
FunctionEntity functionEntity = new FunctionEntity(GenericName.build(methodName), this.latestValidContainer(),
idGenerator.generateId(),GenericName.build(returnType));
functionEntity.setLine(startLine);
addToRepo(functionEntity);
this.typeOrFileContainer().addFunction(functionEntity);
pushToStack(functionEntity);
functionEntity.addThrowTypes(throwedType.stream().map(item->GenericName.build(item)).collect(Collectors.toList()));
return functionEntity;
}
public FunctionEntity foundMethodDeclarator(String methodName, Integer startLine) {
FunctionEntity functionEntity = new FunctionEntity(GenericName.build(methodName), this.latestValidContainer(),
idGenerator.generateId(),null);
functionEntity.setLine(startLine);
addToRepo(functionEntity);
this.typeOrFileContainer().addFunction(functionEntity);
pushToStack(functionEntity);
return functionEntity;
}
public FunctionEntity foundMethodDeclarator(ContainerEntity containerEntity, String methodName, Integer startLine) {
FunctionEntity functionEntity = new FunctionEntity(GenericName.build(methodName), containerEntity,
idGenerator.generateId(),null);
functionEntity.setLine(startLine);
addToRepo(functionEntity);
containerEntity.addFunction(functionEntity);
pushToStack(functionEntity);
functionEntity.addThrowTypes(new ArrayList<>());
return functionEntity;
}
public void foundNewImport(Import imported) {
currentFileEntity.addImport(imported);
}
public TypeEntity currentType() {
for (int i = entityStack.size() - 1; i >= 0; i--) {
Entity t = entityStack.get(i);
if (t instanceof TypeEntity)
return (TypeEntity) t;
}
return null;
}
public ContainerEntity typeOrFileContainer() {
for (int i = entityStack.size() - 1; i >= 0; i--) {
Entity t = entityStack.get(i);
if (t instanceof TypeEntity)
return (ContainerEntity) t;
if (t instanceof FileEntity) {
return (ContainerEntity)t;
}
}
return null;
}
public FunctionEntity currentFunction() {
for (int i = entityStack.size() - 1; i >= 0; i--) {
Entity t = entityStack.get(i);
if (t instanceof FunctionEntity)
return (FunctionEntity) t;
}
return null;
}
public FileEntity currentFile() {
return currentFileEntity;
}
public ContainerEntity globalScope() {
Entity global = entityRepo.getEntity(EntityRepo.GLOBAL_SCOPE_NAME);
if (global==null) {
global = new PackageEntity(EntityRepo.GLOBAL_SCOPE_NAME,idGenerator.generateId());
addToRepo(global);
}
return (ContainerEntity)global;
}
public Entity latestValidContainer() {
for (int i = entityStack.size() - 1; i >= 0; i--) {
Entity t = entityStack.get(i);
if (t instanceof FunctionEntity)
return t;
if (t instanceof TypeEntity)
return t;
if (t instanceof FileEntity)
return t;
}
return null;
}
public ContainerEntity lastContainer() {
for (int i = entityStack.size() - 1; i >= 0; i--) {
Entity t = entityStack.get(i);
if (t instanceof ContainerEntity)
return (ContainerEntity) t;
}
return null;
}
public void foundImplements(GenericName typeName) {
currentType().addImplements(typeName);
}
public void foundExtends(String className) {
foundExtends(GenericName.build(className));
}
public void foundExtends(GenericName typeName) {
if (currentType()==null) {
System.out.println("error: type do not exist");
return ;
}
currentType().addExtends(typeName);
}
public void foundMixin(String name) {
foundMixin(GenericName.build(name));
}
public void foundMixin(GenericName name) {
lastContainer().addMixin(name);
}
public void foundTypeParametes(GenericName typeName) {
lastContainer().addTypeParameter(typeName);
}
public List<VarEntity> foundVarDefinitions(List<String> varNames, String type, List<GenericName> typeArguments, Integer line) {
return varNames.stream().map(item->foundVarDefinition(item,GenericName.build(type),typeArguments,line)).collect(Collectors.toList());
}
public VarEntity foundVarDefinition(ContainerEntity container,String varName,Integer line) {
if (container==null) {
System.out.println("fallback to file container for var " + varName + " in file "+ currentFile().getRawName());
container = currentFile();
}
VarEntity var = getVarInLocalFile(container,GenericName.build(varName));
if (var!=null) return var;
var = new VarEntity(GenericName.build(varName), null, container, idGenerator.generateId());
var.setLine(line);
container.addVar(var);
addToRepo(var);
return var;
}
public VarEntity foundGlobalVarDefinition(ContainerEntity container,String varName,Integer line) {
if (container==null) {
System.out.println("fallback to file container for var " + varName + " in file "+ currentFile().getRawName());
container = currentFile();
}
VarEntity var = getVarInLocalFile(container,GenericName.build(varName));
if (var!=null) return var;
var = new VarEntity(GenericName.build(varName), null, container, idGenerator.generateId());
container.addVar(var);
var.setLine(line);
var.setQualifiedName(var.getRawName().toString());
addToRepo(var);
return var;
}
public VarEntity foundVarDefinition(String varName, GenericName type, List<GenericName> typeArguments,Integer line) {
VarEntity var = new VarEntity(GenericName.build(varName), type, lastContainer(), idGenerator.generateId());
var.setLine(line);
var.addTypeParameter(typeArguments);
lastContainer().addVar(var);
addToRepo(var);
return var;
}
public VarEntity addMethodParameter(String paramName) {
if (currentFunction()==null) return null;
VarEntity varEntity = new VarEntity(GenericName.build(paramName),null,currentFunction(),idGenerator.generateId());
currentFunction().addParameter(varEntity);
addToRepo(varEntity);
return varEntity;
}
public VarEntity foundEnumConstDefinition(String varName,Integer line) {
GenericName type = lastContainer().getRawName();
return foundVarDefinition(varName,type,new ArrayList<>(),line);
}
protected Stack<Entity> entityStack = new Stack<Entity>();
protected void pushToStack(Entity entity) {
entityStack.push(entity);
}
public void exitLastedEntity() {
//we never pop up the lastest one (FileEntity)
if (entityStack.size()>1)
entityStack.pop();
}
private VarEntity getVarInLocalFile(ContainerEntity container, GenericName varName) {
Entity entity = bindingResolver.resolveName(container, varName, false);
if (entity ==null ) return null;
Entity fileEntity = entity.getAncestorOfType(FileEntity.class);
if (fileEntity ==null ){
//may not exist in fileEntity, for example global vars
}else{
if (!fileEntity.equals(currentFileEntity)) return null;
if (entity instanceof VarEntity) return (VarEntity)entity;
}
return null;
}
public Entity foundEntityWithName(GenericName rawName) {
return bindingResolver.resolveName(lastContainer(), rawName, true);
}
public void addToRepo(Entity entity) {
entityRepo.add(entity);
}
}
| 11,090 | 32.306306 | 135 |
java
|
depends
|
depends-master/src/main/java/depends/extractor/ParserCreator.java
|
/*
MIT License
Copyright (c) 2018-2019 Gang ZHANG
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package depends.extractor;
public interface ParserCreator {
FileParser createFileParser();
}
| 1,176 | 35.78125 | 78 |
java
|
depends
|
depends-master/src/main/java/depends/extractor/FileParser.java
|
/*
MIT License
Copyright (c) 2018-2019 Gang ZHANG
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package depends.extractor;
import depends.entity.FileEntity;
import depends.entity.repo.EntityRepo;
import multilang.depends.util.file.FileUtil;
import java.io.IOException;
public abstract class FileParser {
protected EntityRepo entityRepo;
/**
* parse files
* @param filePath
* @throws IOException
*/
public final void parse(String filePath) throws IOException{
filePath = FileUtil.uniqFilePath(filePath);
/* If file already exist, skip it */
FileEntity fileEntity = entityRepo.getFileEntity(filePath);
if (fileEntity!=null) {
System.out.println("already parsed " + filePath + "...skip");
if (!fileEntity.isInProjectScope())
fileEntity.setInProjectScope(true);
}else {
System.out.println("parsing " + filePath + "...");
parseFile(filePath);
entityRepo.completeFile(filePath);
}
}
/**
* The actual file parser - it should put parsed entities into entityRepo;
* @param filePath - it is alread unique file path name
* @throws IOException
*/
protected abstract void parseFile(String filePath) throws IOException;
protected boolean isPhase2Files(String filePath){
return false;
}
}
| 2,221 | 31.676471 | 78 |
java
|
depends
|
depends-master/src/main/java/depends/extractor/IncludedFileLocator.java
|
/*
MIT License
Copyright (c) 2018-2019 Gang ZHANG
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package depends.extractor;
import multilang.depends.util.file.FileUtil;
import java.io.File;
import java.util.List;
/**
* Search file in all included path
*/
public final class IncludedFileLocator {
private List<String> includesPath;
public IncludedFileLocator(List<String> includedPath) {
this.includesPath = includedPath;
}
/**
* Search file in all included path
* * search the filename directly
* * search the filename based in given start path (usually current working directory
* * search the filename in all included paths
* @param dirPath
* @param importedFilename
* @return
*/
public String uniqFileName(String dirPath, String importedFilename) {
if (FileUtil.existFile(importedFilename)) return FileUtil.uniqFilePath(importedFilename);
if (dirPath!=null) {
String path = dirPath + File.separator + importedFilename;
if (FileUtil.existFile(path)) return FileUtil.uniqFilePath(path);
}
for (String includePath:includesPath) {
String path = includePath + File.separator + importedFilename;
if (FileUtil.existFile(path)) return FileUtil.uniqFilePath(path);
}
return null;
}
}
| 2,223 | 34.301587 | 91 |
java
|
depends
|
depends-master/src/main/java/depends/extractor/AbstractLangProcessor.java
|
/*
MIT License
Copyright (c) 2018-2019 Gang ZHANG
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package depends.extractor;
import depends.entity.Entity;
import depends.entity.FileEntity;
import depends.entity.repo.BuiltInType;
import depends.entity.repo.EntityRepo;
import depends.entity.repo.InMemoryEntityRepo;
import depends.relations.ImportLookupStrategy;
import depends.relations.IBindingResolver;
import multilang.depends.util.file.FileTraversal;
import multilang.depends.util.file.FileUtil;
import org.codehaus.plexus.util.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.IOException;
import java.lang.management.ManagementFactory;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
abstract public class AbstractLangProcessor {
/**
* The name of the lang
*
* @return
*/
public abstract String supportedLanguage();
/**
* The file suffixes in the lang
*
* @return
*/
public abstract String[] fileSuffixes();
/**
* Strategy of how to lookup types and entities in the lang.
*
* @return
*/
public abstract ImportLookupStrategy getImportLookupStrategy();
/**
* The builtInType of the lang.
*
* @return
*/
public abstract BuiltInType getBuiltInType();
/**
* The language specific file parser
*
* @param fileFullPath
* @return
*/
public abstract FileParser createFileParser();
public IBindingResolver bindingResolver;
protected EntityRepo entityRepo;
protected String inputSrcPath;
public String[] includeDirs;
private Set<UnsolvedBindings> potentialExternalDependencies;
private List<String> includePaths;
private static Logger logger = LoggerFactory.getLogger(AbstractLangProcessor.class);
public AbstractLangProcessor() {
entityRepo = new InMemoryEntityRepo();
}
/**
* The process steps of build dependencies. Step 1: parse all files, add
* entities and expression into repositories Step 2: resolve bindings of files
* (if not resolved yet) Step 3: identify dependencies
*
* @param inputDir
* @param includeDir
* @param bindingResolver
* @return
*/
public EntityRepo buildDependencies(String inputDir, String[] includeDir, IBindingResolver bindingResolver) {
this.inputSrcPath = inputDir;
this.includeDirs = includeDir;
this.bindingResolver = bindingResolver;
logger.info("Start parsing files...");
parseAllFiles();
markAllEntitiesScope();
if (logger.isInfoEnabled()) {
logger.info("Resolve types and bindings of variables, methods and expressions.... " + this.inputSrcPath);
logger.info("Heap Information: " + ManagementFactory.getMemoryMXBean().getHeapMemoryUsage());
}
resolveBindings();
if (logger.isInfoEnabled()) {
System.gc();
logger.info("Heap Information: " + ManagementFactory.getMemoryMXBean().getHeapMemoryUsage());
}
return entityRepo;
}
private void markAllEntitiesScope() {
entityRepo.getFileEntities().stream().forEach(entity -> {
Entity file = entity.getAncestorOfType(FileEntity.class);
try {
if (!file.getQualifiedName().startsWith(this.inputSrcPath)) {
entity.setInScope(false);
}
} catch (Exception e) {
}
});
}
/**
* @return unsolved bindings
*/
public void resolveBindings() {
System.out.println("Resolve types and bindings of variables, methods and expressions....");
this.potentialExternalDependencies = bindingResolver.resolveAllBindings(this.isEagerExpressionResolve());
if (getExternalDependencies().size() > 0) {
System.out.println("There are " + getExternalDependencies().size() + " items are potential external dependencies.");
}
System.out.println("types and bindings resolved successfully...");
}
private final void parseAllFiles() {
System.out.println("Start parsing files...");
Set<String> phase2Files = new HashSet<>();
FileTraversal fileTransversal = new FileTraversal(new FileTraversal.IFileVisitor() {
@Override
public void visit(File file) {
String fileFullPath = file.getAbsolutePath();
if (!fileFullPath.startsWith(inputSrcPath)) {
return;
}
parseFile(fileFullPath, phase2Files);
}
});
fileTransversal.extensionFilter(this.fileSuffixes());
fileTransversal.travers(this.inputSrcPath);
for (String f : phase2Files) {
parseFile(f, phase2Files);
}
System.out.println("all files procceed successfully...");
}
protected void parseFile(String fileFullPath, Set<String> phase2Files) {
FileParser fileParser = createFileParser();
try {
if (fileParser.isPhase2Files(fileFullPath)){
phase2Files.add(fileFullPath);
}else {
fileParser.parse(fileFullPath);
}
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
System.err.println("error occoured during parse file " + fileFullPath);
e.printStackTrace();
}
}
public List<String> includePaths() {
if (this.includePaths ==null) {
this.includePaths = buildIncludePath();
}
return includePaths;
}
private List<String> buildIncludePath() {
includePaths = new ArrayList<String>();
for (String path : includeDirs) {
if (FileUtils.fileExists(path)) {
path = FileUtil.uniqFilePath(path);
if (!includePaths.contains(path))
includePaths.add(path);
}
path = this.inputSrcPath + File.separator + path;
if (FileUtils.fileExists(path)) {
path = FileUtil.uniqFilePath(path);
if (!includePaths.contains(path))
includePaths.add(path);
}
}
return includePaths;
}
public EntityRepo getEntityRepo() {
return this.entityRepo;
}
public abstract List<String> supportedRelations();
public Set<UnsolvedBindings> getExternalDependencies() {
return potentialExternalDependencies;
}
public String getRelationMapping(String relation) {
return relation;
}
/**
* Whether to resolve expression immediately during parse
* @return
*/
public boolean isEagerExpressionResolve(){
return false;
}
/**
* Call as Impl:
* implicit call (for example polymorphic in cpp)
* @return
*/
public boolean supportCallAsImpl(){return false;};
}
| 7,076 | 27.421687 | 119 |
java
|
depends
|
depends-master/src/main/java/depends/extractor/UnsolvedBindings.java
|
package depends.extractor;
import depends.entity.Entity;
public class UnsolvedBindings {
private String rawName;
private Entity fromEntity;
public UnsolvedBindings(String rawName, Entity fromEntity) {
this.rawName = rawName;
this.fromEntity = fromEntity;
}
public String getRawName() {
return rawName;
}
public Entity getFromEntity() {
return fromEntity;
}
public String getSourceDisplay() {
if (fromEntity==null) return "<not known>";
return fromEntity.getQualifiedName();
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((fromEntity == null) ? 0 : fromEntity.hashCode());
result = prime * result + ((rawName == null) ? 0 : rawName.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
UnsolvedBindings other = (UnsolvedBindings) obj;
if (fromEntity == null) {
if (other.fromEntity != null)
return false;
} else if (!fromEntity.equals(other.fromEntity))
return false;
if (rawName == null) {
if (other.rawName != null)
return false;
} else if (!rawName.equals(other.rawName))
return false;
return true;
}
public void setFromEntity(Entity fromEntity) {
this.fromEntity = fromEntity;
}
}
| 1,370 | 20.421875 | 79 |
java
|
depends
|
depends-master/src/main/java/depends/extractor/ruby/RubyHandlerContext.java
|
/*
MIT License
Copyright (c) 2018-2019 Gang ZHANG
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package depends.extractor.ruby;
import depends.entity.Entity;
import depends.entity.FileEntity;
import depends.entity.PackageEntity;
import depends.entity.repo.EntityRepo;
import depends.extractor.FileParser;
import depends.extractor.HandlerContext;
import depends.extractor.IncludedFileLocator;
import depends.extractor.ParserCreator;
import depends.importtypes.FileImport;
import depends.relations.IBindingResolver;
import multilang.depends.util.file.FileUtil;
import java.util.Collection;
public class RubyHandlerContext extends HandlerContext {
private IncludedFileLocator includedFileLocator;
private ParserCreator parserCreator;
public RubyHandlerContext(EntityRepo entityRepo,
IncludedFileLocator includedFileLocator,
IBindingResolver bindingResolver, ParserCreator parserCreator) {
super(entityRepo, bindingResolver);
this.includedFileLocator = includedFileLocator;
this.parserCreator = parserCreator;
}
public Entity foundNamespace(String nampespaceName, Integer startLine) {
Entity parentEntity = currentFile();
if (latestValidContainer()!=null)
parentEntity = latestValidContainer();
PackageEntity pkgEntity = new PackageEntity(nampespaceName, parentEntity,idGenerator.generateId());
entityRepo.add(pkgEntity);
entityStack.push(pkgEntity);
return pkgEntity;
}
public void processSpecialFuncCall(String methodName, Collection<String> params, Integer startLine) {
// Handle Import relation
if(methodName.equals("require") || methodName.equals("require_relative")) {
for (String importedFilename:params) {
if (!importedFilename.endsWith(".rb")) importedFilename = importedFilename + ".rb";
String dir = FileUtil.getLocatedDir(currentFile().getRawName().uniqName());
String inclFileName = includedFileLocator.uniqFileName(dir,importedFilename);
if (inclFileName==null) {
System.err.println("Warning: cannot found included file " + importedFilename );
continue;
}
FileParser importedParser = parserCreator.createFileParser();
try {
importedParser.parse(inclFileName);
} catch (Exception e) {
System.err.println("parsing error in "+inclFileName);
}
foundNewImport(new FileImport(inclFileName));
}
}
// Handle Extend relation
else if (methodName.equals("extend")) {
for (String moduleName:params) {
foundExtends(moduleName);
}
}
// Handle mixin relation
else if (methodName.equals("include")) {
for (String moduleName:params) {
foundMixin(moduleName);
}
}
// attribute methods
else if (methodName.equals("attr_accessor")||methodName.equals("attr_writer")||methodName.equals("attr_reader")) {
for (String name:params) {
name = name.replace(":", ""); //remove symbol
foundMethodDeclarator(name,startLine);
}
}
}
public FileEntity startFile(String fileName) {
return super.startFile(false, fileName);
}
}
| 4,013 | 36.166667 | 116 |
java
|
depends
|
depends-master/src/main/java/depends/extractor/ruby/RubyBuiltInType.java
|
/*
MIT License
Copyright (c) 2018-2019 Gang ZHANG
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package depends.extractor.ruby;
import depends.entity.repo.BuiltInType;
public class RubyBuiltInType extends BuiltInType {
@Override
public String[] getBuiltInMethods() {
return new String[] { "+", "-", "*", "/", "**", "%", "&", "<", "<=", ">", ">=", "==", "!=", "===", "<<", ">>",
"~", "!", "^", "new", "!~", "<=>", "===", "=~", "[]", "class", "clone", "define_singleton_method", "display",
"dup", "enum_for", "eql?", "extend", "freeze", "frozen?", "inspect", "instance_of?",
"instance_variable_defined?", "instance_variable_get", "instance_variable_set", "instance_variables",
"is_a?", "itself", "kind_of?", "method", "methods", "nil?", "object_id", "private_methods",
"protected_methods", "public_method", "public_methods", "public_send", "remove_instance_variable",
"respond_to?", "respond_to_missing?", "send", "singleton_class", "singleton_method",
"singleton_methods", "taint", "tainted?", "tap", "then", "to_enum", "to_s", "trust", "untaint",
"untrust", "untrusted?", "yield_self","each","join","empty?","copy","size" };
}
}
| 2,153 | 46.866667 | 113 |
java
|
depends
|
depends-master/src/main/java/depends/extractor/ruby/RubyImportLookupStrategy.java
|
/*
MIT License
Copyright (c) 2018-2019 Gang ZHANG
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package depends.extractor.ruby;
import depends.entity.repo.EntityRepo;
import depends.extractor.cpp.CppImportLookupStrategy;
public class RubyImportLookupStrategy extends CppImportLookupStrategy {
public RubyImportLookupStrategy(EntityRepo repo) {
super(repo);
}
}
| 1,364 | 36.916667 | 78 |
java
|
depends
|
depends-master/src/main/java/depends/extractor/ruby/RubyProcessor.java
|
/*
MIT License
Copyright (c) 2018-2019 Gang ZHANG
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package depends.extractor.ruby;
import depends.entity.repo.BuiltInType;
import depends.extractor.AbstractLangProcessor;
import depends.extractor.FileParser;
import depends.extractor.IncludedFileLocator;
import depends.extractor.ParserCreator;
import depends.extractor.ruby.jruby.JRubyFileParser;
import depends.relations.ImportLookupStrategy;
import java.util.ArrayList;
import java.util.List;
import static depends.deptypes.DependencyType.*;
public class RubyProcessor extends AbstractLangProcessor implements ParserCreator{
private static final String LANG = "ruby";
private static final String[] SUFFIX = new String[] {".rb"};
@Override
public String supportedLanguage() {
return LANG;
}
@Override
public String[] fileSuffixes() {
return SUFFIX;
}
@Override
public FileParser createFileParser() {
return new JRubyFileParser(entityRepo,new IncludedFileLocator(super.includePaths()), bindingResolver,this);
}
@Override
public ImportLookupStrategy getImportLookupStrategy() {
return new RubyImportLookupStrategy(entityRepo);
}
@Override
public BuiltInType getBuiltInType() {
return new RubyBuiltInType();
}
@Override
public List<String> supportedRelations() {
ArrayList<String> depedencyTypes = new ArrayList<>();
depedencyTypes.add(IMPORT);
depedencyTypes.add(CONTAIN);
depedencyTypes.add(INHERIT);
depedencyTypes.add(CALL);
depedencyTypes.add(PARAMETER);
depedencyTypes.add(RETURN);
depedencyTypes.add(SET);
depedencyTypes.add(CREATE);
depedencyTypes.add(USE);
depedencyTypes.add(CAST);
depedencyTypes.add(THROW);
depedencyTypes.add(MIXIN);
return depedencyTypes;
}
@Override
public boolean isEagerExpressionResolve(){
return true;
}
}
| 2,800 | 28.797872 | 109 |
java
|
depends
|
depends-master/src/main/java/depends/extractor/ruby/jruby/ExpressionUsage.java
|
/*
MIT License
Copyright (c) 2018-2019 Gang ZHANG
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package depends.extractor.ruby.jruby;
import depends.entity.*;
import depends.entity.repo.IdGenerator;
import depends.extractor.ruby.RubyHandlerContext;
import depends.relations.IBindingResolver;
import org.jrubyparser.ast.*;
import java.util.List;
public class ExpressionUsage {
RubyHandlerContext context;
IdGenerator idGenerator;
IBindingResolver bindingResolver;
private RubyParserHelper helper;
public ExpressionUsage(RubyHandlerContext context, IdGenerator idGenerator, RubyParserHelper helper,
IBindingResolver bindingResolver) {
this.context = context;
this.idGenerator = idGenerator;
this.bindingResolver = bindingResolver;
this.helper = helper;
}
public Expression foundExpression(Node ctx) {
if (ctx instanceof RootNode)
return null;
if (ctx instanceof BlockNode)
return null;
Expression expression = findExpression(ctx);
if (expression != null)
return expression;
Expression parent = findParentInStack(ctx);
/* create expression and link it with parent */
expression = new Expression(idGenerator.generateId());
expression.setLine(ctx.getPosition().getStartLine());
expression.setText(ctx.toString());
expression.setParent(parent);
if (ctx instanceof NewlineNode) {
expression.setStatement(true);
}
context.lastContainer().addExpression(ctx, expression);
if (ctx instanceof ILiteralNode && !(ctx instanceof ListNode)) {
expression.setIdentifier("<literal>");
expression.setRawType(TypeEntity.buildInType.getQualifiedName());
} else if (ctx instanceof TrueNode || ctx instanceof FalseNode) {
expression.setIdentifier("<boolean>");
expression.setRawType(TypeEntity.buildInType.getQualifiedName());
} else if (ctx instanceof AndNode || ctx instanceof OrNode) {
expression.setIdentifier("<logical>");
expression.setRawType(TypeEntity.buildInType.getQualifiedName());
} else if (ctx instanceof ConstNode) {
expression.setRawType(helper.getName(ctx));
expression.setIdentifier(helper.getName(ctx));
} else if (ctx instanceof LocalVarNode || ctx instanceof GlobalVarNode || ctx instanceof ClassVarNode
|| ctx instanceof InstVarNode || ctx instanceof Colon3Node) {
expression.setIdentifier(helper.getName(ctx));
}
if (ctx instanceof AssignableNode) {
expression.setSet(true);
} else if (helper.isFunctionCall(ctx)) {
String name = helper.getName(ctx);
expression.setCall(true);
if (name.equals("new")) {
expression.setCreate(true);
List<Node> childNodes = ctx.childNodes();
if (childNodes.size() > 0) {
expression.setIdentifier(helper.getName(ctx.childNodes().get(0)));
} else {
expression.setIdentifier(context.currentType().getRawName());
}
expression.setRawType(expression.getIdentifier());
expression.disableDriveTypeFromChild();
} else if (name.equals("raise")) {
expression.setThrow (true);
} else if (helper.isArithMeticOperator(name)) {
expression.setIdentifier("<operator>");
expression.setRawType(TypeEntity.buildInType.getQualifiedName());
} else {
expression.setIdentifier(name);
expression.setRawType(helper.getReciever(ctx));
if (expression.getRawType() != null) {
expression.setDot(true);
}
if (ctx instanceof VCallNode || ctx instanceof FCallNode) {
expression.disableDriveTypeFromChild();
}
}
}
deduceVarTypeInCaseOfAssignment(ctx, expression);
deduceReturnTypeInCaseOfReturn(ctx, expression);
return expression;
}
/**
* Auto deduce variable type from assignment. for example: c = C.new then c is
* type of C
*
* @param node
* @param expression
*/
private void deduceVarTypeInCaseOfAssignment(Node node, Expression expression) {
Node parentNode = node.getParent();
if (parentNode instanceof AssignableNode) {
ContainerEntity scope = helper.getScopeOfVar((AssignableNode) parentNode, this.context);
VarEntity var = scope.lookupVarLocally(helper.getName(parentNode));
if (var != null) {
expression.addDeducedTypeVar(var);
}
}
}
private void deduceReturnTypeInCaseOfReturn(Node ctx, Expression expression) {
FunctionEntity currentFunction = context.currentFunction();
if (currentFunction == null)
return;
if (ctx instanceof ReturnNode) {
expression.addDeducedTypeFunction(currentFunction);
}
}
private Expression findParentInStack(Node ctx) {
if (ctx == null)
return null;
if (ctx.getParent() == null)
return null;
if (context.lastContainer() == null) {
return null;
}
if (context.lastContainer().expressions().containsKey(ctx.getParent()))
return context.lastContainer().expressions().get(ctx.getParent());
return findParentInStack(ctx.getParent());
}
private Expression findExpression(Node ctx) {
if (ctx == null)
return null;
if (ctx.getParent() == null)
return null;
if (context.lastContainer() == null) {
return null;
}
return context.lastContainer().expressions().get(ctx);
}
}
| 6,012 | 33.959302 | 103 |
java
|
depends
|
depends-master/src/main/java/depends/extractor/ruby/jruby/JRubyVisitor.java
|
/*
MIT License
Copyright (c) 2018-2019 Gang ZHANG
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package depends.extractor.ruby.jruby;
import depends.entity.*;
import depends.entity.repo.EntityRepo;
import depends.extractor.ParserCreator;
import depends.extractor.IncludedFileLocator;
import depends.extractor.ruby.RubyHandlerContext;
import depends.relations.IBindingResolver;
import org.jrubyparser.ast.*;
import org.jrubyparser.util.NoopVisitor;
import java.util.ArrayList;
import java.util.Collection;
public class JRubyVisitor extends NoopVisitor {
private RubyHandlerContext context;
RubyParserHelper helper = RubyParserHelper.getInst();
private ExpressionUsage expressionUsage;
public JRubyVisitor(String fileFullPath, EntityRepo entityRepo, IncludedFileLocator includedFileLocator,
IBindingResolver bindingResolver, ParserCreator parserCreator) {
this.context = new RubyHandlerContext(entityRepo, includedFileLocator, bindingResolver, parserCreator);
expressionUsage = new ExpressionUsage(context, entityRepo, helper, bindingResolver);
context.startFile(fileFullPath);
}
@Override
public Object visitAliasNode(AliasNode node) {
context.foundNewAlias(node.getNewNameString(), node.getOldNameString());
return super.visitAliasNode(node);
}
@Override
public Object visitModuleNode(ModuleNode node) {
String name = helper.getName(node.getCPath());
context.foundNamespace(name,node.getPosition().getStartLine()+1);
super.visitModuleNode(node);
context.exitLastedEntity();
return null;
}
@Override
public Object visitClassNode(ClassNode node) {
TypeEntity type = context.foundNewType(helper.getName(node.getCPath()),node.getPosition().getStartLine()+1);
Node superNode = node.getSuper();
if (superNode instanceof ConstNode ||
superNode instanceof SymbolNode ||
superNode instanceof Colon2ConstNode ||
superNode instanceof Colon3Node) {
String superName = helper.getName(superNode);
context.foundExtends(superName);
}else{
if (superNode != null) {
System.err.println("cannot support the super node style" + superNode.toString());
}
}
super.visitClassNode(node);
context.exitLastedEntity();
return null;
}
@Override
public Object visitRootNode(RootNode node) {
return super.visitRootNode(node);
}
@Override
public Object visitFCallNode(FCallNode node) {
String fname = helper.getName(node);
Collection<String> params = getParams(node);
context.processSpecialFuncCall(fname, params, node.getPosition().getStartLine()+1);
return super.visitFCallNode(node);
}
private Collection<String> getParams(IArgumentNode node) {
Node args = node.getArgs();
Collection<String> params = new ArrayList<>();
if (args instanceof ArrayNode) {
ArrayNode argArray = (ArrayNode) args;
for (Node arg : argArray.childNodes()) {
if (arg instanceof StrNode) {
params.add(((StrNode) arg).getValue());
} else if (arg instanceof ConstNode) {
params.add(((ConstNode) arg).getName());
}
}
}
return params;
}
@Override
public Object visitCallNode(CallNode node) {
String fname = helper.getName(node);
Collection<String> params = getParams(node);
addCallToReceiverVar(node, fname);
context.processSpecialFuncCall(fname, params, node.getPosition().getStartLine()+1);
return super.visitCallNode(node);
}
private void addCallToReceiverVar(CallNode node, String fname) {
if (helper.isCommonOperator(fname))return;
Node varNode = node.getReceiver();
GenericName varName = GenericName.build(helper.getName(varNode));
if (varName==null) return;
Entity var = context.foundEntityWithName(varName);
if (var != null && var instanceof VarEntity) {
VarEntity varEntity = (VarEntity) var;
varEntity.addFunctionCall(GenericName.build(fname));
}
}
@Override
public Object visitUnaryCallNode(UnaryCallNode node) {
String fname = helper.getName(node);
Collection<String> params = new ArrayList<>();
context.processSpecialFuncCall(fname, params, node.getPosition().getStartLine()+1);
return super.visitUnaryCallNode(node);
}
/**
* VCallNode is just a function call without parameter
*/
@Override
public Object visitVCallNode(VCallNode node) {
return super.visitVCallNode(node);
}
@Override
public Object visitDefnNode(DefnNode node) {
FunctionEntity method = context.foundMethodDeclarator(node.getName(),node.getPosition().getStartLine()+1);
method.setLine(node.getPosition().getStartLine()+1);
super.visitDefnNode(node);
context.exitLastedEntity();
return null;
}
@Override
public Object visitDefsNode(DefsNode node) {
boolean handled = false;
Node varNode = node.getReceiver();
if (varNode instanceof SelfNode) {
//will be handled by context.foundMethodDeclarator(node.getName(), null, new ArrayList<>());
} else if (varNode instanceof ConstNode) {
String className = ((INameNode) varNode).getName();
Entity entity = context.foundEntityWithName(GenericName.build(className));
if (entity != null && entity instanceof ContainerEntity) {
FunctionEntity method = context.foundMethodDeclarator(((ContainerEntity) entity), node.getName(),node.getPosition().getStartLine()+1);
method.setLine(node.getPosition().getStartLine()+1);
handled = true;
}
} else if (varNode instanceof INameNode) {
String varName = ((INameNode) varNode).getName();
Entity var = context.foundEntityWithName(GenericName.build(varName));
if (var != null && var instanceof ContainerEntity) {
FunctionEntity method = context.foundMethodDeclarator(((ContainerEntity) var), node.getName(),node.getPosition().getStartLine()+1);
method.setLine(node.getPosition().getStartLine()+1);
handled = true;
}
}
if (!handled) {
// fallback to add it to last container
FunctionEntity method = context.foundMethodDeclarator(node.getName(),node.getPosition().getStartLine()+1);
method.setLine(node.getPosition().getStartLine()+1);
}
super.visitDefsNode(node);
context.exitLastedEntity();
return null;
}
@Override
public Object visitGlobalVarNode(GlobalVarNode node) {
context.foundVarDefinition(context.globalScope(), node.getName(),node.getPosition().getStartLine()+1);
return super.visitGlobalVarNode(node);
}
@Override
public Object visitInstVarNode(InstVarNode node) {
context.foundVarDefinition(context.currentType(), node.getName(),node.getPosition().getStartLine()+1);
return super.visitInstVarNode(node);
}
@Override
public Object visitClassVarAsgnNode(ClassVarAsgnNode node) {
context.foundVarDefinition(helper.getScopeOfVar(node,context), node.getName(),node.getPosition().getStartLine()+1);
return super.visitClassVarAsgnNode(node);
}
@Override
public Object visitClassVarDeclNode(ClassVarDeclNode node) {
context.foundVarDefinition(context.currentType(), node.getName(),node.getPosition().getStartLine()+1);
return super.visitClassVarDeclNode(node);
}
@Override
public Object visitClassVarNode(ClassVarNode node) {
context.foundVarDefinition(context.currentType(), node.getName(),node.getPosition().getStartLine()+1);
return super.visitClassVarNode(node);
}
@Override
public Object visitLocalVarNode(LocalVarNode node) {
return super.visitLocalVarNode(node);
}
@Override
public Object visitDVarNode(DVarNode node) {
context.foundVarDefinition(context.lastContainer(), node.getName(),node.getPosition().getStartLine()+1);
return super.visitDVarNode(node);
}
@Override
public Object visitDAsgnNode(DAsgnNode node) {
context.foundVarDefinition(helper.getScopeOfVar(node,context), node.getName(),node.getPosition().getStartLine()+1);
expressionUsage.foundExpression(node);
return super.visitDAsgnNode(node);
}
@Override
public Object visitGlobalAsgnNode(GlobalAsgnNode node) {
context.foundVarDefinition(helper.getScopeOfVar(node,context), node.getName(),node.getPosition().getStartLine()+1);
return super.visitGlobalAsgnNode(node);
}
@Override
public Object visitInstAsgnNode(InstAsgnNode node) {
context.foundVarDefinition(helper.getScopeOfVar(node,context), node.getName(),node.getPosition().getStartLine()+1);
return super.visitInstAsgnNode(node);
}
@Override
public Object visitArgumentNode(ArgumentNode node) {
String paramName = node.getName();
context.addMethodParameter(paramName);
return super.visitArgumentNode(node);
}
@Override
public Object visitLocalAsgnNode(LocalAsgnNode node) {
context.foundVarDefinition(helper.getScopeOfVar(node,context), node.getName(),node.getPosition().getStartLine()+1);
return super.visitLocalAsgnNode(node);
}
@Override
protected Object visit(Node node) {
expressionUsage.foundExpression(node);
return super.visit(node);
}
}
| 9,707 | 33.425532 | 138 |
java
|
depends
|
depends-master/src/main/java/depends/extractor/ruby/jruby/JRubyFileParser.java
|
/*
MIT License
Copyright (c) 2018-2019 Gang ZHANG
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package depends.extractor.ruby.jruby;
import depends.entity.repo.EntityRepo;
import depends.extractor.FileParser;
import depends.extractor.IncludedFileLocator;
import depends.extractor.ParserCreator;
import depends.relations.IBindingResolver;
import org.antlr.v4.runtime.CharStream;
import org.antlr.v4.runtime.CharStreams;
import org.jrubyparser.CompatVersion;
import org.jrubyparser.Parser;
import org.jrubyparser.ast.Node;
import org.jrubyparser.lexer.SyntaxException;
import org.jrubyparser.parser.ParserConfiguration;
import java.io.IOException;
import java.io.StringReader;
public class JRubyFileParser extends FileParser {
private IncludedFileLocator includesFileLocator;
private IBindingResolver bindingResolver;
private ParserCreator parserCreator;
public JRubyFileParser( EntityRepo entityRepo,
IncludedFileLocator includesFileLocator,
IBindingResolver bindingResolver, ParserCreator parserCreator) {
this.entityRepo = entityRepo;
this.includesFileLocator = includesFileLocator;
this.bindingResolver = bindingResolver;
this.parserCreator = parserCreator;
}
@SuppressWarnings("unchecked")
@Override
protected void parseFile(String fileFullPath) throws IOException {
CharStream input = CharStreams.fromFileName(fileFullPath);
Parser rubyParser = new Parser();
StringReader in = new StringReader(input.toString());
CompatVersion version = CompatVersion.RUBY2_3;
ParserConfiguration config = new ParserConfiguration(0, version);
try {
Node node = rubyParser.parse(fileFullPath, in, config);
JRubyVisitor parser = new JRubyVisitor(fileFullPath, entityRepo, includesFileLocator, bindingResolver,parserCreator);
node.accept(parser);
}catch(SyntaxException e) {
System.out.println("parsing error in "+e.getPosition() + "(" + e.getMessage() + ")");
}catch (Exception e){
e.printStackTrace();
}
}
}
| 3,021 | 38.763158 | 120 |
java
|
depends
|
depends-master/src/main/java/depends/extractor/ruby/jruby/RubyParserHelper.java
|
/*
MIT License
Copyright (c) 2018-2019 Gang ZHANG
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package depends.extractor.ruby.jruby;
import java.util.ArrayList;
import java.util.List;
import org.jrubyparser.ast.AssignableNode;
import org.jrubyparser.ast.CallNode;
import org.jrubyparser.ast.ClassVarAsgnNode;
import org.jrubyparser.ast.ClassVarDeclNode;
import org.jrubyparser.ast.Colon2Node;
import org.jrubyparser.ast.Colon3Node;
import org.jrubyparser.ast.ConstDeclNode;
import org.jrubyparser.ast.DAsgnNode;
import org.jrubyparser.ast.DefsNode;
import org.jrubyparser.ast.FCallNode;
import org.jrubyparser.ast.GlobalAsgnNode;
import org.jrubyparser.ast.INameNode;
import org.jrubyparser.ast.InstAsgnNode;
import org.jrubyparser.ast.ListNode;
import org.jrubyparser.ast.LocalAsgnNode;
import org.jrubyparser.ast.MultipleAsgnNode;
import org.jrubyparser.ast.Node;
import org.jrubyparser.ast.UnaryCallNode;
import org.jrubyparser.ast.VCallNode;
import depends.entity.ContainerEntity;
import depends.extractor.ruby.RubyBuiltInType;
import depends.extractor.ruby.RubyHandlerContext;
public class RubyParserHelper {
private static RubyParserHelper inst = new RubyParserHelper();
public static RubyParserHelper getInst() {
return inst;
}
private RubyBuiltInType buildInType;
private RubyParserHelper() {
this.buildInType = new RubyBuiltInType();
}
public String getName(Node node) {
String name = "";
if (node instanceof INameNode) {
name = ((INameNode)node).getName();
if (node instanceof Colon2Node) {
Node left = ((Colon2Node)node).getLeftNode();
if (left!=null) {
name = getName(left) + "."+name;
}
}else if (node instanceof Colon3Node) {
name = "."+name;
}
}
return name.length()>0?name:null;
}
public boolean isFunctionCall(Node ctx) {
return ctx instanceof CallNode ||
ctx instanceof FCallNode ||
ctx instanceof UnaryCallNode ||
ctx instanceof VCallNode;
}
public List<String> getName(AssignableNode ctx) {
List<String> names = new ArrayList<>();
if (ctx instanceof ClassVarAsgnNode) {
names.add(((ClassVarAsgnNode)ctx).getName());
}else if (ctx instanceof ClassVarDeclNode) {
names.add(((ClassVarDeclNode)ctx).getName());
}else if (ctx instanceof ConstDeclNode) {
names.add(((ConstDeclNode)ctx).getName());
}else if (ctx instanceof DAsgnNode) {
names.add(((DAsgnNode)ctx).getName());
}else if (ctx instanceof GlobalAsgnNode) {
names.add(((GlobalAsgnNode)ctx).getName());
}else if (ctx instanceof InstAsgnNode) {
names.add(((InstAsgnNode)ctx).getName());
}else if (ctx instanceof LocalAsgnNode) {
names.add(((LocalAsgnNode)ctx).getName());
}else if (ctx instanceof MultipleAsgnNode) {
ListNode pre = ((MultipleAsgnNode)ctx).getPre();
if (pre!=null) {
//TODO: support multiple assignment
}
}
return names;
}
public String getReciever(Node ctx) {
Node receiver = null;
if (ctx instanceof CallNode) {
receiver = ((CallNode)ctx).getReceiver();
}else if (ctx instanceof DefsNode) {
receiver = ((DefsNode)ctx).getReceiver();
}
if (receiver==null) {
return null;
}
if (receiver instanceof INameNode) {
return this.getName(receiver);
}
return null;
}
public ContainerEntity getScopeOfVar(AssignableNode node, RubyHandlerContext context) {
if (node instanceof LocalAsgnNode) return context.lastContainer();
if (node instanceof InstAsgnNode) return context.currentType();
if (node instanceof ClassVarAsgnNode) return context.currentType();
if (node instanceof GlobalAsgnNode) return context.globalScope();
if (node instanceof DAsgnNode) return context.lastContainer();
return context.lastContainer();
}
public boolean isArithMeticOperator(String name) {
return name.equals("+") ||
name.equals("-") ||
name.equals("*") ||
name.equals("/") ||
name.equals("**") ||
name.equals("%") ||
name.equals("&") ||
name.equals("<") ||
name.equals("<=") ||
name.equals(">") ||
name.equals(">=") ||
name.equals("==") ||
name.equals("!=") ||
name.equals("===") ||
name.equals("<<") ||
name.equals(">>") ||
name.equals("~") ||
name.equals("!") ||
name.equals("^");
}
public boolean isCommonOperator(String name) {
return this.buildInType.isBuildInMethod(name);
}
}
| 5,298 | 30.921687 | 88 |
java
|
depends
|
depends-master/src/main/java/depends/extractor/kotlin/KotlinHandlerContext.java
|
package depends.extractor.kotlin;
import depends.entity.repo.EntityRepo;
import depends.extractor.java.JavaHandlerContext;
import depends.relations.IBindingResolver;
public class KotlinHandlerContext extends JavaHandlerContext {
public KotlinHandlerContext(EntityRepo entityRepo, IBindingResolver bindingResolver) {
super(entityRepo, bindingResolver);
}
}
| 365 | 23.4 | 87 |
java
|
depends
|
depends-master/src/main/java/depends/extractor/kotlin/KotlinProcessor.java
|
package depends.extractor.kotlin;
import depends.entity.repo.BuiltInType;
import depends.extractor.AbstractLangProcessor;
import depends.extractor.FileParser;
import depends.extractor.java.JavaBuiltInType;
import depends.extractor.java.JavaImportLookupStrategy;
import depends.relations.ImportLookupStrategy;
import java.util.ArrayList;
import java.util.List;
import static depends.deptypes.DependencyType.*;
public class KotlinProcessor extends AbstractLangProcessor {
public KotlinProcessor() {
super();
}
@Override
public String supportedLanguage() {
return "kotlin[on-going]";
}
@Override
public String[] fileSuffixes() {
return new String[] {".kt"};
}
@Override
public ImportLookupStrategy getImportLookupStrategy() {
return new JavaImportLookupStrategy(entityRepo);
}
@Override
public BuiltInType getBuiltInType() {
return new JavaBuiltInType();
}
@Override
public FileParser createFileParser() {
return new KotlinFileParser(entityRepo, bindingResolver);
}
@Override
public boolean isEagerExpressionResolve(){
return true;
}
@Override
public List<String> supportedRelations() {
ArrayList<String> depedencyTypes = new ArrayList<>();
depedencyTypes.add(IMPORT);
depedencyTypes.add(CONTAIN);
depedencyTypes.add(IMPLEMENT);
depedencyTypes.add(INHERIT);
depedencyTypes.add(CALL);
depedencyTypes.add(PARAMETER);
depedencyTypes.add(RETURN);
depedencyTypes.add(SET);
depedencyTypes.add(CREATE);
depedencyTypes.add(USE);
depedencyTypes.add(CAST);
depedencyTypes.add(THROW);
depedencyTypes.add(ANNOTATION);
return depedencyTypes;
}
}
| 1,614 | 21.746479 | 60 |
java
|
depends
|
depends-master/src/main/java/depends/extractor/kotlin/KotlinListener.java
|
package depends.extractor.kotlin;
import depends.entity.repo.EntityRepo;
import depends.extractor.kotlin.KotlinParser.ImportHeaderContext;
import depends.extractor.kotlin.KotlinParser.PackageHeaderContext;
import depends.importtypes.ExactMatchImport;
import depends.relations.IBindingResolver;
public class KotlinListener extends KotlinParserBaseListener {
private KotlinHandlerContext context;
public KotlinListener(String fileFullPath, EntityRepo entityRepo, IBindingResolver bindingResolver) {
this.context = new KotlinHandlerContext(entityRepo, bindingResolver);
context.startFile(fileFullPath);
}
@Override
public void enterPackageHeader(PackageHeaderContext ctx) {
if (ctx.identifier()!=null) {
context.foundNewPackage(ContextHelper.getName(ctx.identifier()));
}
super.enterPackageHeader(ctx);
}
@Override
public void enterImportHeader(ImportHeaderContext ctx) {
context.foundNewImport(new ExactMatchImport(ContextHelper.getName(ctx.identifier())));
//TODO: alias of import
if (ctx.importAlias()!=null) {
}
super.enterImportHeader(ctx);
}
}
| 1,092 | 27.763158 | 102 |
java
|
depends
|
depends-master/src/main/java/depends/extractor/kotlin/KotlinFileParser.java
|
package depends.extractor.kotlin;
import depends.entity.repo.EntityRepo;
import depends.extractor.FileParser;
import depends.relations.IBindingResolver;
import org.antlr.v4.runtime.CharStream;
import org.antlr.v4.runtime.CharStreams;
import org.antlr.v4.runtime.CommonTokenStream;
import org.antlr.v4.runtime.Lexer;
import org.antlr.v4.runtime.tree.ParseTreeWalker;
import java.io.IOException;
public class KotlinFileParser extends FileParser {
@Override
protected void parseFile(String fileFullPath) throws IOException {
CharStream input = CharStreams.fromFileName(fileFullPath);
Lexer lexer = new KotlinLexer(input);
CommonTokenStream tokens = new CommonTokenStream(lexer);
KotlinParser parser = new KotlinParser(tokens);
KotlinListener bridge = new KotlinListener(fileFullPath, entityRepo, bindingResolver);
ParseTreeWalker walker = new ParseTreeWalker();
walker.walk(bridge, parser.kotlinFile());
}
private IBindingResolver bindingResolver;
public KotlinFileParser(EntityRepo entityRepo, IBindingResolver bindingResolver) {
this.entityRepo = entityRepo;
this.bindingResolver = bindingResolver;
}
}
| 1,145 | 32.705882 | 88 |
java
|
depends
|
depends-master/src/main/java/depends/extractor/kotlin/ContextHelper.java
|
package depends.extractor.kotlin;
import depends.extractor.kotlin.KotlinParser.IdentifierContext;
import depends.extractor.kotlin.KotlinParser.SimpleIdentifierContext;
public class ContextHelper {
public static String getName(IdentifierContext identifier) {
StringBuffer sb = new StringBuffer();
for (SimpleIdentifierContext id:identifier.simpleIdentifier()) {
if (sb.length()>0) {
sb.append(".");
}
sb.append(id.getText());
}
return sb.toString();
}
}
| 480 | 23.05 | 69 |
java
|
depends
|
depends-master/src/main/java/depends/extractor/kotlin/context/ExpressionUsage.java
|
package depends.extractor.kotlin.context;
import depends.entity.repo.EntityRepo;
import depends.extractor.kotlin.KotlinHandlerContext;
public class ExpressionUsage {
public ExpressionUsage(KotlinHandlerContext context, EntityRepo entityRepo) {
// TODO Auto-generated constructor stub
}
}
| 296 | 21.846154 | 78 |
java
|
depends
|
depends-master/src/main/java/depends/extractor/empty/EmptyBuiltInType.java
|
/*
MIT License
Copyright (c) 2018-2019 Gang ZHANG
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package depends.extractor.empty;
import depends.entity.repo.BuiltInType;
public class EmptyBuiltInType extends BuiltInType {
}
| 1,208 | 38 | 78 |
java
|
depends
|
depends-master/src/main/java/depends/extractor/empty/EmptyImportLookupStategy.java
|
/*
MIT License
Copyright (c) 2018-2019 Gang ZHANG
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package depends.extractor.empty;
import depends.entity.Entity;
import depends.entity.FileEntity;
import depends.entity.repo.EntityRepo;
import depends.extractor.UnsolvedBindings;
import depends.importtypes.Import;
import depends.relations.ImportLookupStrategy;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
public class EmptyImportLookupStategy extends ImportLookupStrategy {
public EmptyImportLookupStategy(EntityRepo repo) {
super(repo);
}
@Override
public Entity lookupImportedType(String name, FileEntity fileEntity) {
return null;
}
@Override
public List<Entity> getImportedRelationEntities(List<Import> importedNames) {
return new ArrayList<Entity>();
}
@Override
public List<Entity> getImportedTypes(List<Import> importedNames,Set<UnsolvedBindings> unsolvedBindings) {
return new ArrayList<Entity>();
}
@Override
public List<Entity> getImportedFiles(List<Import> importedNames) {
return new ArrayList<Entity>();
}
public boolean supportGlobalNameLookup() {
return false;
}
}
| 2,125 | 30.264706 | 106 |
java
|
depends
|
depends-master/src/main/java/depends/extractor/pom/PomLocator.java
|
/*
MIT License
Copyright (c) 2018-2019 Gang ZHANG
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package depends.extractor.pom;
import java.io.File;
import java.util.List;
import multilang.depends.util.file.FileUtil;
public class PomLocator {
private List<String> includePaths;
private PomParent pomParent;
public PomLocator(List<String> includePaths, PomParent pomParent) {
this.includePaths = includePaths;
this.pomParent = pomParent;
}
public String getLocation() {
StringBuilder sb = new StringBuilder();
sb.append(pomParent.groupId.replace(".", File.separator));
sb.append(File.separator);
sb.append(pomParent.artifactId);
sb.append(File.separator);
sb.append(pomParent.version);
sb.append(File.separator);
sb.append(pomParent.artifactId);
sb.append("-");
sb.append(pomParent.version);
sb.append(".pom");
for (String includePath:includePaths) {
String path = includePath+File.separator+sb.toString();
if (FileUtil.existFile(path)) {
return FileUtil.uniqFilePath(path);
}
}
return null;
}
}
| 2,035 | 30.8125 | 78 |
java
|
depends
|
depends-master/src/main/java/depends/extractor/pom/PomListener.java
|
/*
MIT License
Copyright (c) 2018-2019 Gang ZHANG
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package depends.extractor.pom;
import depends.entity.Expression;
import depends.entity.GenericName;
import depends.entity.VarEntity;
import depends.entity.repo.EntityRepo;
import depends.extractor.FileParser;
import depends.extractor.xml.XMLParser.ElementContext;
import depends.extractor.xml.XMLParserBaseListener;
import depends.relations.IBindingResolver;
import org.antlr.v4.runtime.ParserRuleContext;
import java.io.IOException;
import java.util.List;
import java.util.Stack;
public class PomListener extends XMLParserBaseListener {
private PomHandlerContext context;
private EntityRepo entityRepo;
PomArtifactEntity currentEntity;
private VarEntity currentVar;
Expression currentExpression;
private PomParent pomParent;
private PomProcessor parseCreator;
private List<String> includePaths;
private IBindingResolver IBindingResolver;
private Stack<PomCoords> pomCoords= new Stack<>();
public PomListener(String fileFullPath, EntityRepo entityRepo, List<String> includePaths, PomProcessor parseCreator,
IBindingResolver bindingResolver) {
this.context = new PomHandlerContext(entityRepo);
this.entityRepo = entityRepo;
this.parseCreator = parseCreator;
this.includePaths = includePaths;
this.IBindingResolver = bindingResolver;
context.startFile(fileFullPath);
}
@Override
public void enterElement(ElementContext ctx) {
String name = ctx.Name(0).getText();
if (name.equals("project")) {
pomCoords.push(new PomCoords());
currentEntity = new PomArtifactEntity("", context.currentFile(), entityRepo.generateId());
} else if (name.equals("plugin")) {
pomCoords.push(new PomCoords());
currentExpression = new Expression(entityRepo.generateId());
currentExpression.setRawType("");
} else if (name.equals("dependency")) {
pomCoords.push(new PomCoords());
currentVar = new VarEntity(GenericName.build(""), GenericName.build(""),
currentEntity, entityRepo.generateId());
} else if (name.equals("parent")) {
pomCoords.push(new PomCoords());
pomParent = new PomParent("");
}
// Add attribute
else if (name.equals("groupId")) {
peekPomCoords().groupId = getContentValueOf(ctx);
} else if (name.equals("artifactId")) {
peekPomCoords().artifactId = getContentValueOf(ctx);
} else if (name.equals("version")) {
peekPomCoords().version = getContentValueOf(ctx);
} else if ("properties".equals(getParentElementName(ctx))) {
if (ctx.content() != null) {
currentEntity.addProperty(name, getContentValueOf(ctx));
}
}
super.enterElement(ctx);
}
private PomCoords peekPomCoords() {
return pomCoords.peek();
}
private String getContentValueOf(ElementContext ctx) {
String text = ctx.content().getText();
if (text == null)
return "";
if (text.contains("${"))
text = currentEntity.replaceProperty(text);
return text;
}
@Override
public void exitElement(ElementContext ctx) {
String name = ctx.Name(0).getText();
if (name.equals("project")) {
if (pomParent != null) {
peekPomCoords().fillFromIfNull(pomParent);
}
currentEntity.setRawName(peekPomCoords().getGenericNamePath());
currentEntity.setQualifiedName(currentEntity.getRawName().uniqName());
entityRepo.add(currentEntity);
pomCoords.pop();
} else if (name.equals("plugin")) {
peekPomCoords().sureFillVersion(includePaths);
currentExpression.setRawType(peekPomCoords().getGenericNamePath());
currentEntity.addExpression(ctx, currentExpression);
pomCoords.pop();
} else if (name.equals("dependency")) {
peekPomCoords().sureFillVersion(includePaths);
currentVar.setRawType(peekPomCoords().getGenericNamePath());
//TODO: Depends currently has a limitation: var name cannot be same as var type
//To be fixed in future
currentVar.setRawName(new GenericName("_" + currentVar.getRawType().getName()));
currentEntity.addVar(currentVar);
pomCoords.pop();
} else if (name.equals("parent")) {
pomParent.buildFrom(peekPomCoords());
context.currentFile().addImport(pomParent);
String parentFileName = new PomLocator(includePaths, pomParent).getLocation();
if (parentFileName != null) {
FileParser importedParser = parseCreator.createFileParser();
try {
importedParser.parse(parentFileName);
} catch (IOException e) {
System.err.println("error occurred during parse "+ parentFileName);
}
}
pomCoords.pop();
context.currentFile().inferLocalLevelEntities(IBindingResolver);
}
super.exitElement(ctx);
}
private String getParentElementName(ParserRuleContext node) {
node = node.getParent();
if (node == null)
return "project";
node = node.getParent();
if (!(node instanceof ElementContext))
return "project";
ElementContext p = (ElementContext) node;
String name = p.Name().get(0).getText();
return name;
}
}
| 5,883 | 34.445783 | 117 |
java
|
depends
|
depends-master/src/main/java/depends/extractor/pom/PomFileParser.java
|
/*
MIT License
Copyright (c) 2018-2019 Gang ZHANG
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package depends.extractor.pom;
import depends.entity.repo.EntityRepo;
import depends.extractor.FileParser;
import depends.extractor.xml.XMLLexer;
import depends.extractor.xml.XMLParser;
import depends.relations.IBindingResolver;
import org.antlr.v4.runtime.CharStream;
import org.antlr.v4.runtime.CharStreams;
import org.antlr.v4.runtime.CommonTokenStream;
import org.antlr.v4.runtime.Lexer;
import org.antlr.v4.runtime.tree.ParseTreeWalker;
import java.io.IOException;
import java.util.List;
public class PomFileParser extends FileParser {
private PomProcessor parseCreator;
private List<String> includePaths;
private IBindingResolver bindingResolver;
public PomFileParser(EntityRepo entityRepo, List<String> includePaths, PomProcessor pomProcessor, IBindingResolver bindingResolver) {
this.entityRepo = entityRepo;
this.parseCreator = pomProcessor;
this.includePaths = includePaths;
this.bindingResolver = bindingResolver;
}
@Override
protected void parseFile(String fileFullPath) throws IOException {
CharStream input = CharStreams.fromFileName(fileFullPath);
Lexer lexer = new XMLLexer(input);
CommonTokenStream tokens = new CommonTokenStream(lexer);
XMLParser parser = new XMLParser(tokens);
PomListener bridge = new PomListener(fileFullPath, entityRepo, includePaths,parseCreator, bindingResolver);
ParseTreeWalker walker = new ParseTreeWalker();
walker.walk(bridge, parser.document());
}
}
| 2,573 | 38 | 134 |
java
|
depends
|
depends-master/src/main/java/depends/extractor/pom/PomProcessor.java
|
/*
MIT License
Copyright (c) 2018-2019 Gang ZHANG
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package depends.extractor.pom;
import depends.entity.repo.BuiltInType;
import depends.extractor.AbstractLangProcessor;
import depends.extractor.FileParser;
import depends.extractor.empty.EmptyBuiltInType;
import depends.relations.ImportLookupStrategy;
import java.util.ArrayList;
import java.util.List;
import static depends.deptypes.DependencyType.PomParent;
import static depends.deptypes.DependencyType.*;
public class PomProcessor extends AbstractLangProcessor {
@Override
public String supportedLanguage() {
return "pom";
}
@Override
public String[] fileSuffixes() {
return new String[] {".pom"};
}
@Override
public ImportLookupStrategy getImportLookupStrategy() {
return new PomImportLookupStategy(entityRepo);
}
@Override
public BuiltInType getBuiltInType() {
return new EmptyBuiltInType();
}
@Override
public FileParser createFileParser() {
return new PomFileParser(entityRepo,includePaths(),this, bindingResolver);
}
@Override
public List<String> supportedRelations() {
ArrayList<String> depedencyTypes = new ArrayList<>();
depedencyTypes.add(PomParent);
depedencyTypes.add(PomPlugin);
depedencyTypes.add(PomDependency);
return depedencyTypes;
}
@Override
public String getRelationMapping(String relation) {
if (relation.equals(IMPORT)) return PomParent;
if (relation.equals(USE)) return PomPlugin;
if (relation.equals(CONTAIN)) return PomDependency;
return relation;
}
}
| 2,526 | 29.083333 | 78 |
java
|
depends
|
depends-master/src/main/java/depends/extractor/pom/PomHandlerContext.java
|
/*
MIT License
Copyright (c) 2018-2019 Gang ZHANG
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package depends.extractor.pom;
import depends.entity.FileEntity;
import depends.entity.repo.EntityRepo;
import depends.extractor.HandlerContext;
public class PomHandlerContext extends HandlerContext {
public PomHandlerContext(EntityRepo entityRepo) {
super(entityRepo, null);
}
public FileEntity startFile(String fileName) {
return super.startFile(false, fileName);
}
}
| 1,461 | 34.658537 | 78 |
java
|
depends
|
depends-master/src/main/java/depends/extractor/pom/PomParent.java
|
/*
MIT License
Copyright (c) 2018-2019 Gang ZHANG
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package depends.extractor.pom;
import depends.importtypes.Import;
public class PomParent extends Import {
public PomParent(String content) {
super(content);
}
public String groupId = "";
public String artifactId = "";
public String version = "";
public void buildFrom(PomCoords pomCoords) {
this.groupId = pomCoords.groupId;
this.artifactId = pomCoords.artifactId;
this.version = pomCoords.version;
this.setContent(pomCoords.getPath());
}
}
| 1,542 | 32.543478 | 78 |
java
|
depends
|
depends-master/src/main/java/depends/extractor/pom/PomCoords.java
|
/*
MIT License
Copyright (c) 2018-2019 Gang ZHANG
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package depends.extractor.pom;
import java.io.File;
import java.util.List;
import depends.entity.GenericName;
import multilang.depends.util.file.FileUtil;
public class PomCoords {
public PomCoords() {
}
public String groupId = "";
public String artifactId = "";
public String version = "";
public String getPath() {
return groupId+"."+artifactId+"_" +version+"_" ;
}
public void fillFromIfNull(PomParent pomParent) {
if (groupId=="") groupId = pomParent.groupId;
if (artifactId=="") artifactId = pomParent.artifactId;
if (version=="") version = pomParent.version;
}
public GenericName getGenericNamePath() {
return new GenericName(getPath());
}
public void sureFillVersion(List<String> includePaths) {
if (version!="") return;
StringBuilder sb = new StringBuilder();
sb.append(this.groupId.replace(".", File.separator));
sb.append(File.separator);
sb.append(this.artifactId);
sb.append(File.separator);
for (String includePath:includePaths) {
String path = includePath+File.separator+sb.toString();
if (FileUtil.existFile(path)) {
File f = new File(path);
String max = "";
for (String d:f.list()) {
if (d.compareTo(max)>0)
max = d;
}
version = max;
}
}
}
}
| 2,324 | 30.418919 | 78 |
java
|
depends
|
depends-master/src/main/java/depends/extractor/pom/PomImportLookupStategy.java
|
/*
MIT License
Copyright (c) 2018-2019 Gang ZHANG
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package depends.extractor.pom;
import depends.entity.Entity;
import depends.entity.repo.EntityRepo;
import depends.extractor.empty.EmptyImportLookupStategy;
import depends.importtypes.Import;
import java.util.ArrayList;
import java.util.List;
public class PomImportLookupStategy extends EmptyImportLookupStategy {
public PomImportLookupStategy(EntityRepo repo) {
super(repo);
}
@Override
public List<Entity> getImportedRelationEntities(List<Import> importedList) {
ArrayList<Entity> result = new ArrayList<>();
for (Import importedItem:importedList) {
Entity imported = repo.getEntity(importedItem.getContent());
if (imported==null) continue;
result.add(imported);
}
return result;
}
@Override
public boolean supportGlobalNameLookup() {
return true;
}
}
| 1,869 | 32.392857 | 78 |
java
|
depends
|
depends-master/src/main/java/depends/extractor/pom/PomArtifactEntity.java
|
/*
MIT License
Copyright (c) 2018-2019 Gang ZHANG
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package depends.extractor.pom;
import java.util.Collection;
import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import depends.entity.Entity;
import depends.entity.FileEntity;
import depends.entity.GenericName;
import depends.entity.TypeEntity;
public class PomArtifactEntity extends TypeEntity {
HashMap<String,String> properties;
public PomArtifactEntity(String simpleName, Entity parent, Integer id) {
super(GenericName.build(simpleName), parent, id);
properties = new HashMap<>();
}
public String getProperty(String key) {
String v = properties.get(key);
if (v!=null) return v;
FileEntity file = (FileEntity)(this.getAncestorOfType(FileEntity.class));
Collection<Entity> parents = file.getImportedRelationEntities();
for(Entity parent:parents) {
if (parent instanceof PomArtifactEntity) {
return ((PomArtifactEntity)parent).getProperty(key);
}
}
return null;
}
public void addProperty(String key, String value) {
value = replaceProperty(value);
properties.put(key, value);
}
public String replaceProperty(String content) {
Pattern pattern = Pattern.compile("\\$\\{[_A-Za-z0-9\\-\\.]*\\}");
Matcher matcher = pattern.matcher(content);
String s = content;
while (matcher.find()) {
String keyPattern = matcher.group();
String key = keyPattern.replace("${", "").replace("}","");
String value = getProperty(key);
if (value!=null)
s = s.replace(keyPattern, value);
}
return s;
}
}
| 2,608 | 32.883117 | 78 |
java
|
depends
|
depends-master/src/main/java/depends/extractor/cpp/Scanner.java
|
package depends.extractor.cpp;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import org.eclipse.cdt.core.dom.parser.IScannerExtensionConfiguration;
import org.eclipse.cdt.core.dom.parser.cpp.GPPScannerExtensionConfiguration;
import org.eclipse.cdt.core.index.IIndexFileLocation;
import org.eclipse.cdt.core.parser.CodeReader;
import org.eclipse.cdt.core.parser.FileContent;
import org.eclipse.cdt.core.parser.IScanner;
import org.eclipse.cdt.core.parser.IScannerInfo;
import org.eclipse.cdt.core.parser.IncludeFileContentProvider;
import org.eclipse.cdt.core.parser.NullLogService;
import org.eclipse.cdt.core.parser.ParserLanguage;
import org.eclipse.cdt.core.parser.ScannerInfo;
import org.eclipse.cdt.internal.core.parser.IMacroDictionary;
import org.eclipse.cdt.internal.core.parser.scanner.CPreprocessor;
import org.eclipse.cdt.internal.core.parser.scanner.InternalFileContent;
import org.eclipse.cdt.internal.core.parser.scanner.InternalFileContent.InclusionKind;
import org.eclipse.cdt.internal.core.parser.scanner.InternalFileContentProvider;
import depends.extractor.cpp.cdt.FileCache;
public class Scanner {
/**
* Build a scanner used for parser
* @param file -- the scanned source file
* @param macroMap -- the macro maps
* @param sysIncludePath -- the included paths
* @param shouldScanInclusionFiles -- whether to scan the included files
* @return the scanner
*/
public static IScanner buildScanner(String file, Map<String, String> macroMap, List<String> sysIncludePath, boolean shouldScanInclusionFiles) {
String content = "";
try {
CodeReader cr = new CodeReader(file);
content = new String(cr.buffer);
} catch (IOException e) {
}
IScannerInfo scannerInfo = new ScannerInfo(macroMap, sysIncludePath.toArray(new String[] {}));
IScannerExtensionConfiguration configuration = GPPScannerExtensionConfiguration.getInstance(scannerInfo);
InternalFileContentProvider ifcp = new InternalFileContentProvider() {
@Override
public InternalFileContent getContentForInclusion(String filePath, IMacroDictionary macroDictionary) {
InternalFileContent ifc = null;
if (!shouldScanInclusionFiles) {
ifc = new InternalFileContent(filePath, InclusionKind.SKIP_FILE);
}else {
ifc = FileCache.getInstance().get(filePath);
}
if (ifc == null) {
ifc = (InternalFileContent) FileContent.createForExternalFileLocation(filePath);
FileCache.getInstance().put(filePath, ifc);
}
return ifc;
}
@Override
public InternalFileContent getContentForInclusion(IIndexFileLocation ifl, String astPath) {
InternalFileContent c = FileCache.getInstance().get(ifl);
if (c == null) {
c = (InternalFileContent) FileContent.create(ifl);
FileCache.getInstance().put(ifl, c);
}
return c;
}
};
ParserLanguage lang = ParserLanguage.CPP;
if (file.endsWith(".c"))
lang = ParserLanguage.C;
IScanner scanner = new CPreprocessor(FileContent.create(file, content.toCharArray()), scannerInfo, lang,
new NullLogService(), configuration, IncludeFileContentProvider.getEmptyFilesProvider());
scanner.setProcessInactiveCode(true);
return scanner;
}
}
| 3,189 | 38.382716 | 144 |
java
|
depends
|
depends-master/src/main/java/depends/extractor/cpp/MacroRepo.java
|
package depends.extractor.cpp;
import depends.extractor.cpp.cdt.GPPParserExtensionConfigurationExtension;
import multilang.depends.util.file.FileUtil;
import org.eclipse.cdt.core.dom.ast.IASTPreprocessorMacroDefinition;
import org.eclipse.cdt.core.dom.ast.IMacroBinding;
import org.eclipse.cdt.core.parser.IScanner;
import org.eclipse.cdt.core.parser.NullLogService;
import org.eclipse.cdt.core.parser.ParserMode;
import org.eclipse.cdt.internal.core.dom.parser.AbstractGNUSourceCodeParser;
import org.eclipse.cdt.internal.core.dom.parser.cpp.GNUCPPSourceParser;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public abstract class MacroRepo {
private Map<String, String> defaultMacroMap = new HashMap<>();
/**
* Generate default macro from system include paths
* @param sysIncludePath
* @return
*/
public Map<String, String> buildDefaultMap(List<String> sysIncludePath) {
for (String p : sysIncludePath) {
if (!FileUtil.isDirectory(p)) {
IScanner scanner = Scanner.buildScanner(p,defaultMacroMap, sysIncludePath, true);
if (scanner==null) continue;
AbstractGNUSourceCodeParser sourceCodeParser = new GNUCPPSourceParser(scanner,
ParserMode.COMPLETE_PARSE, new NullLogService(), new GPPParserExtensionConfigurationExtension(),
null);
sourceCodeParser.parse();
Map<String, IMacroBinding> macros = scanner.getMacroDefinitions();
for (String key : macros.keySet()) {
String exp = new String(macros.get(key).getExpansion());
defaultMacroMap.put(macros.get(key).toString(), exp);
}
}
}
return defaultMacroMap;
}
public Map<String, String> getDefaultMap() {
return defaultMacroMap;
}
public abstract Map<String, String> get(String incl);
public abstract void putMacros(String fileFullPath, Map<String, String> macroMap,
IASTPreprocessorMacroDefinition[] macroDefinitions);
}
| 1,888 | 32.732143 | 102 |
java
|
depends
|
depends-master/src/main/java/depends/extractor/cpp/MacroFileRepo.java
|
package depends.extractor.cpp;
import depends.entity.repo.EntityRepo;
import multilang.depends.util.file.TemporaryFile;
import org.eclipse.cdt.core.dom.ast.IASTPreprocessorMacroDefinition;
import org.eclipse.cdt.core.dom.ast.IMacroBinding;
import java.io.*;
import java.util.HashMap;
import java.util.Map;
public class MacroFileRepo extends MacroRepo{
private EntityRepo entityRepo;
public MacroFileRepo(EntityRepo entityRepo) {
this.entityRepo = entityRepo;
}
@Override
public Map<String, String> get(String incl) {
Integer fileId = entityRepo.getEntity(incl).getId();
try
{
FileInputStream fileIn = new FileInputStream(TemporaryFile.getInstance().macroPath(fileId));
ObjectInputStream in = new ObjectInputStream(fileIn);
@SuppressWarnings("unchecked")
Map<String, String> macros = (Map<String, String>) in.readObject();
if (macros==null) macros = new HashMap<>();
in.close();
fileIn.close();
return macros;
}catch(IOException | ClassNotFoundException i)
{
return new HashMap<>();
}
}
@Override
public void putMacros(String fileFullPath, Map<String, String> macroMap,
IASTPreprocessorMacroDefinition[] macroDefinitions) {
if (macroDefinitions.length==0 && macroMap.size()==0) return;
Integer fileId = entityRepo.getEntity(fileFullPath).getId();
Map<String, String> macros = get(fileFullPath);
macros.putAll(macroMap);
for (IASTPreprocessorMacroDefinition def:macroDefinitions) {
macros.put(((IMacroBinding)def.getName().resolveBinding()).toString(), new String(def.getExpansion()));
}
try {
FileOutputStream fileOut = new FileOutputStream(TemporaryFile.getInstance().macroPath(fileId));
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(macros);
out.close();
fileOut.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
| 1,940 | 29.328125 | 106 |
java
|
depends
|
depends-master/src/main/java/depends/extractor/cpp/CppProcessor.java
|
/*
MIT License
Copyright (c) 2018-2019 Gang ZHANG
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package depends.extractor.cpp;
import depends.entity.repo.BuiltInType;
import depends.extractor.AbstractLangProcessor;
import depends.extractor.FileParser;
import depends.extractor.cpp.cdt.CdtCppFileParser;
import depends.extractor.cpp.cdt.PreprocessorHandler;
import depends.relations.ImportLookupStrategy;
import java.util.ArrayList;
import java.util.List;
import static depends.deptypes.DependencyType.*;
public class CppProcessor extends AbstractLangProcessor {
private static final String LANG = "cpp";
private static final String[] SUFFIX = new String[] { ".cpp", ".cc", ".c", ".c++", ".h", ".hpp", ".hh", ".cxx", ".hxx" };
PreprocessorHandler preprocessorHandler = null;
MacroRepo macroRepo = null;
public CppProcessor() {
super();
}
@Override
public String supportedLanguage() {
return LANG;
}
@Override
public String[] fileSuffixes() {
return SUFFIX;
}
@Override
public FileParser createFileParser() {
if (macroRepo == null) {
macroRepo = new MacroEhcacheRepo(entityRepo);
macroRepo.buildDefaultMap(super.includePaths());
}
if (preprocessorHandler==null) {
preprocessorHandler = new PreprocessorHandler(super.inputSrcPath,super.includePaths());
}
return new CdtCppFileParser(entityRepo, preprocessorHandler, bindingResolver, macroRepo);
}
@Override
public ImportLookupStrategy getImportLookupStrategy() {
return new CppImportLookupStrategy(entityRepo);
}
@Override
public BuiltInType getBuiltInType() {
return new CppBuiltInType();
}
@Override
public List<String> supportedRelations() {
ArrayList<String> depedencyTypes = new ArrayList<>();
depedencyTypes.add(IMPORT);
depedencyTypes.add(CONTAIN);
depedencyTypes.add(IMPLEMENT);
depedencyTypes.add(INHERIT);
depedencyTypes.add(CALL);
depedencyTypes.add(PARAMETER);
depedencyTypes.add(RETURN);
depedencyTypes.add(SET);
depedencyTypes.add(CREATE);
depedencyTypes.add(USE);
depedencyTypes.add(CAST);
depedencyTypes.add(THROW);
depedencyTypes.add(LINK);
return depedencyTypes;
}
@Override
public boolean supportCallAsImpl() {
return true;
}
}
| 3,178 | 28.990566 | 122 |
java
|
depends
|
depends-master/src/main/java/depends/extractor/cpp/MacroEhcacheRepo.java
|
package depends.extractor.cpp;
import depends.entity.repo.EntityRepo;
import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;
import org.eclipse.cdt.core.dom.ast.IASTPreprocessorMacroDefinition;
import org.eclipse.cdt.core.dom.ast.IMacroBinding;
import java.util.HashMap;
import java.util.Map;
public class MacroEhcacheRepo extends MacroRepo {
private EntityRepo entityRepo;
CacheManager cacheManager;
Cache cache;
public MacroEhcacheRepo(EntityRepo entityRepo) {
this.entityRepo = entityRepo;
cacheManager = CacheManager.create();
cache = cacheManager.getCache("macros");
}
@Override
public Map<String, String> get(String incl) {
Integer fileId = entityRepo.getEntity(incl).getId();
Element cacheElement = cache.get(buildKey(fileId));
if (cacheElement ==null)
return new HashMap<>();
@SuppressWarnings("unchecked")
Map<String, String> macros = (Map<String, String>) (cacheElement.getObjectValue());
if (macros == null)
macros = new HashMap<>();
return macros;
}
@Override
public void putMacros(String fileFullPath, Map<String, String> macroMap,
IASTPreprocessorMacroDefinition[] macroDefinitions) {
if (macroDefinitions.length == 0 && macroMap.size() == 0)
return;
Integer fileId = entityRepo.getEntity(fileFullPath).getId();
Map<String, String> macros = get(fileFullPath);
macros.putAll(macroMap);
for (IASTPreprocessorMacroDefinition def : macroDefinitions) {
macros.put(((IMacroBinding)def.getName().resolveBinding()).toString(), new String(def.getExpansion()));
}
Element cacheElement = new Element(buildKey(fileId), macros);
cache.put(cacheElement);
}
private String buildKey(Integer fileId) {
return "macro" + fileId;
}
}
| 1,744 | 29.086207 | 106 |
java
|
depends
|
depends-master/src/main/java/depends/extractor/cpp/CppBuiltInType.java
|
/*
MIT License
Copyright (c) 2018-2019 Gang ZHANG
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package depends.extractor.cpp;
import depends.entity.repo.BuiltInType;
public class CppBuiltInType extends BuiltInType {
@Override
protected String[] getBuiltInTypeName() {
return new String[] { "alignas", "alignof", "asm", "auto", "bool", "break", "case", "catch", "char",
"char16_t", "char32_t", "class", "const", "constexpr", "const_cast", "continue", "decltype",
"default", "delete", "do", "double", "dynamic_cast", "else", "enum", "explicit", "export", "extern",
"false", "final", "float", "for", "friend", "goto", "if", "inline", "int", "long", "mutable",
"namespace", "new", "noexcept", "nullptr", "operator", "override", "private", "protected", "public",
"register", "reinterpret_cast", "return", "short", "signed", "sizeof", "static", "static_assert",
"static_cast", "struct", "switch", "template", "this", "thread_local", "throw", "true", "try",
"typedef", "typeid", "typename", "union", "unsigned", "using", "virtual", "void", "volatile",
"wchar_t", "while", "<Built-in>",
"__cplusplus","_cpp_aggregate_bases","__cpp_aggregate_nsdmi","__cpp_alias_templates","__cpp_aligned_new",
"__cpp_attributes","__cpp_binary_literals","__cpp_capture_star_this","__cpp_constexpr","__cpp_decltype",
"__cpp_decltype_auto","__cpp_deduction_guides","__cpp_delegating_constructors",
"__cpp_enumerator_attributes","__cpp_explicit_bool","__cpp_fold_expressions","__cpp_generic_lambdas",
"__cpp_guaranteed_copy_elision","__cpp_hex_float","__cpp_if_constexpr","__cpp_inheriting_constructors",
"__cpp_init_captures","__cpp_initializer_lists","__cpp_inline_variables","__cpp_lambdas",
"__cpp_namespace_attributes","__cpp_noexcept_function_type","__cpp_nontype_template_args",
"__cpp_nontype_template_parameter_auto","__cpp_nontype_template_parameter_class","__cpp_nsdmi"
+ "","__cpp_range_based_for","__cpp_raw_strings","__cpp_ref_qualifiers","__cpp_return_type_deduction"
,"__cpp_rvalue_references","__cpp_sized_deallocation","__cpp_static_assert","__cpp_structured_bindings",
"__cpp_template_template_args","__cpp_threadsafe_static_init","__cpp_unicode_characters","__cpp_unicode_literals",
"__cpp_user_defined_literals","__cpp_variable_templates","__cpp_variadic_templates","__cpp_variadic_using",
"__DATE__","__FILE__","__LINE__","__STDC__","__STDC_ANALYZABLE__","__STDC_HOSTED__","__STDC_IEC_559__",
"__STDC_IEC_559_COMPLEX__","__STDC_ISO_10646__","__STDC_LIB_EXT1__","__STDC_MB_MIGHT_NEQ_WC__",
"__STDC_NO_ATOMICS__","__STDC_NO_COMPLEX__","__STDC_NO_THREADS__","__STDC_NO_VLA__",
"__STDCPP_DEFAULT_NEW_ALIGNMENT__","__STDCPP_STRICT_POINTER_SAFETY__","__STDCPP_THREADS__",
"__STDC_UTF_16__","__STDC_UTF_32__","__STDC_VERSION__","__TIME__"
};
}
@Override
protected String[] getBuiltInTypePrefix() {
return new String[] {"__"};
}
}
| 3,935 | 58.636364 | 120 |
java
|
depends
|
depends-master/src/main/java/depends/extractor/cpp/CppFileParser.java
|
/*
MIT License
Copyright (c) 2018-2019 Gang ZHANG
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package depends.extractor.cpp;
import depends.entity.repo.EntityRepo;
public abstract class CppFileParser extends depends.extractor.FileParser {
public CppFileParser(EntityRepo entityRepo) {
this.entityRepo = entityRepo;
}
}
| 1,310 | 37.558824 | 78 |
java
|
depends
|
depends-master/src/main/java/depends/extractor/cpp/MacroMemoryRepo.java
|
package depends.extractor.cpp;
import org.eclipse.cdt.core.dom.ast.IASTPreprocessorMacroDefinition;
import org.eclipse.cdt.core.dom.ast.IMacroBinding;
import java.util.HashMap;
import java.util.Map;
public class MacroMemoryRepo extends MacroRepo{
private Map<String, Map<String, String>> fileMacroDefinition = new HashMap<>();
private void put(String file, Map<String, String> macros) {
Map<String, String> existingMacros = fileMacroDefinition.get(file);
if (existingMacros==null)
fileMacroDefinition.put(file, macros);
else
existingMacros.putAll(macros);
}
private void put(String file, IASTPreprocessorMacroDefinition[] macroDefinitions) {
Map<String, String> macros = new HashMap<>();
for (IASTPreprocessorMacroDefinition def:macroDefinitions) {
macros.put(((IMacroBinding)def.getName().resolveBinding()).toString(), new String(def.getExpansion()).intern());
}
Map<String, String> existingMacros = fileMacroDefinition.get(file);
if (existingMacros==null)
fileMacroDefinition.put(file, macros);
else
existingMacros.putAll(macros);
}
@Override
public Map<String, String> get(String file) {
return fileMacroDefinition.get(file);
}
@Override
public void putMacros(String fileFullPath,Map<String, String> macroMap, IASTPreprocessorMacroDefinition[] macroDefinitions) {
put(fileFullPath,macroMap);
put(fileFullPath,macroDefinitions);
}
}
| 1,395 | 30.727273 | 126 |
java
|
depends
|
depends-master/src/main/java/depends/extractor/cpp/CppImportLookupStrategy.java
|
/*
MIT License
Copyright (c) 2018-2019 Gang ZHANG
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package depends.extractor.cpp;
import depends.entity.Entity;
import depends.entity.FileEntity;
import depends.entity.GenericName;
import depends.entity.repo.EntityRepo;
import depends.extractor.UnsolvedBindings;
import depends.importtypes.FileImport;
import depends.importtypes.Import;
import depends.relations.ImportLookupStrategy;
import java.util.*;
public class CppImportLookupStrategy extends ImportLookupStrategy {
public CppImportLookupStrategy(EntityRepo repo){
super(repo);
}
@Override
public Entity lookupImportedType(String name, FileEntity fileEntity) {
String importedString = fileEntity.importedSuffixMatch(name);
if (importedString!=null) {
Entity r = repo.getEntity(importedString);
if (r!=null) return r;
}
HashSet<Integer> fileSet = getIncludedFiles(fileEntity);
for (Integer file:fileSet) {
Entity importedItem = repo.getEntity(file);
if (importedItem instanceof FileEntity) {
FileEntity importedFile = (FileEntity) repo.getEntity(file);
if (importedFile==null) continue;
Entity entity = bindingResolver.resolveName(importedFile,GenericName.build(name), false);
if (entity!=null) return entity;
Collection<Entity> namespaces = fileEntity.getImportedTypes();
for (Entity ns:namespaces) {
String nameWithPrefix = ns.getQualifiedName() + "." + name;
entity = bindingResolver.resolveName(importedFile,GenericName.build(nameWithPrefix), false);
if (entity!=null) return entity;
}
}
}
return null;
}
private Map<Integer, HashSet<Integer> > includedFiles = new HashMap<>();
private HashSet<Integer> getIncludedFiles(FileEntity fileEntity) {
if (includedFiles.containsKey(fileEntity.getId())) {
return includedFiles.get(fileEntity.getId());
}
HashSet<Integer> fileSet = new HashSet<>();
foundIncludedFiles(fileSet, fileEntity.getImportedFiles());
includedFiles.put(fileEntity.getId(), fileSet);
return fileSet;
}
private void foundIncludedFiles(HashSet<Integer> fileSet, Collection<Entity> importedFiles) {
for (Entity file:importedFiles) {
if (file==null ) continue;
if (!(file instanceof FileEntity)) continue;
if (fileSet.contains(file.getId())) continue;
fileSet.add(file.getId());
foundIncludedFiles(fileSet,((FileEntity)file).getImportedFiles());
}
}
@Override
public List<Entity> getImportedRelationEntities(List<Import> importedList) {
ArrayList<Entity> result = new ArrayList<>();
for (Import importedItem:importedList) {
if (importedItem instanceof FileImport) {
Entity imported = repo.getEntity(importedItem.getContent());
if (imported==null) continue;
result.add(imported);
}
}
return result;
}
@Override
public List<Entity> getImportedTypes(List<Import> importedList, Set<UnsolvedBindings> unsolvedBindings) {
ArrayList<Entity> result = new ArrayList<>();
for (Import importedItem:importedList) {
if (!(importedItem instanceof FileImport)) {
Entity imported = repo.getEntity(importedItem.getContent());
if (imported==null) {
unsolvedBindings.add(new UnsolvedBindings(importedItem.getContent(),null));
continue;
}
result.add(imported);
}
}
return result;
}
@Override
public List<Entity> getImportedFiles(List<Import> importedList) {
return getImportedRelationEntities(importedList);
}
@Override
public boolean supportGlobalNameLookup() {
return false;
}
}
| 4,492 | 32.529851 | 107 |
java
|
depends
|
depends-master/src/main/java/depends/extractor/cpp/CppHandlerContext.java
|
/*
MIT License
Copyright (c) 2018-2019 Gang ZHANG
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package depends.extractor.cpp;
import depends.entity.*;
import depends.entity.repo.EntityRepo;
import depends.extractor.HandlerContext;
import depends.relations.IBindingResolver;
public class CppHandlerContext extends HandlerContext {
public CppHandlerContext(EntityRepo entityRepo, IBindingResolver IBindingResolver) {
super(entityRepo, IBindingResolver);
}
public Entity foundNamespace(String nampespaceName, int startingLineNumber) {
PackageEntity pkgEntity = new PackageEntity(nampespaceName, currentFile(),idGenerator.generateId());
pkgEntity.setLine(startingLineNumber);
entityRepo.add(pkgEntity);
entityStack.push(pkgEntity);
return pkgEntity;
}
public FunctionEntity foundMethodDeclaratorImplementation(String methodName, GenericName returnType, int startingLineNumber){
FunctionEntity functionEntity = new FunctionEntityImpl(GenericName.build(methodName), this.latestValidContainer(),
idGenerator.generateId(),returnType);
functionEntity.setLine(startingLineNumber);
entityRepo.add(functionEntity);
this.typeOrFileContainer().addFunction(functionEntity);
super.pushToStack(functionEntity);
return functionEntity;
}
public FunctionEntity foundMethodDeclaratorProto(String methodName, GenericName returnType, int startingLineNumber){
FunctionEntity functionEntity = new FunctionEntityProto(GenericName.build(methodName), this.latestValidContainer(),
idGenerator.generateId(),returnType);
functionEntity.setLine(startingLineNumber);
entityRepo.add(functionEntity);
this.typeOrFileContainer().addFunction(functionEntity);
super.pushToStack(functionEntity);
return functionEntity;
}
public FileEntity startFile(String fileName) {
currentFileEntity = new FileEntity(false, fileName, idGenerator.generateId(),true);
pushToStack(currentFileEntity);
entityRepo.add(currentFileEntity);
return currentFileEntity;
}
}
| 2,966 | 39.094595 | 126 |
java
|
depends
|
depends-master/src/main/java/depends/extractor/cpp/cdt/MacroExtractor.java
|
/*
MIT License
Copyright (c) 2018-2019 Gang ZHANG
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package depends.extractor.cpp.cdt;
import depends.entity.FunctionEntity;
import depends.entity.TypeEntity;
import depends.entity.VarEntity;
import depends.extractor.cpp.CppHandlerContext;
import org.eclipse.cdt.core.dom.ast.IASTPreprocessorFunctionStyleMacroDefinition;
import org.eclipse.cdt.core.dom.ast.IASTPreprocessorObjectStyleMacroDefinition;
import org.eclipse.cdt.core.dom.ast.IASTPreprocessorStatement;
import java.util.ArrayList;
public class MacroExtractor {
private final String fileLocation;
private IASTPreprocessorStatement[] statements;
public MacroExtractor(IASTPreprocessorStatement[] statements, String fileLocation) {
this.statements = statements;
this.fileLocation = fileLocation;
}
public void extract(CppHandlerContext context) {
for (int statementIndex=0;statementIndex<statements.length;statementIndex++) {
if (statements[statementIndex] instanceof IASTPreprocessorFunctionStyleMacroDefinition) {
IASTPreprocessorFunctionStyleMacroDefinition funcMacro = (IASTPreprocessorFunctionStyleMacroDefinition)statements[statementIndex];
if (!funcMacro.getFileLocation().getFileName().equals(fileLocation))
continue;
String func = funcMacro.getName().getRawSignature();
FunctionEntity funcEntity = context.foundMethodDeclarator(func, TypeEntity.buildInType.getRawName().uniqName(), new ArrayList<>(),funcMacro.getFileLocation().getStartingLineNumber());
funcEntity.setLine(funcMacro.getFileLocation().getStartingLineNumber());
context.exitLastedEntity();
}else if (statements[statementIndex] instanceof IASTPreprocessorObjectStyleMacroDefinition) {
IASTPreprocessorObjectStyleMacroDefinition varMacro = (IASTPreprocessorObjectStyleMacroDefinition)statements[statementIndex];
if (!varMacro.getFileLocation().getFileName().equals(fileLocation))
continue;
String var = varMacro.getName().getRawSignature();
VarEntity varEntity = context.foundVarDefinition(var, TypeEntity.buildInType.getRawName(), new ArrayList<>(),varMacro.getFileLocation().getStartingLineNumber());
varEntity.setLine(varMacro.getFileLocation().getStartingLineNumber());
}
}
}
}
| 3,223 | 46.411765 | 187 |
java
|
depends
|
depends-master/src/main/java/depends/extractor/cpp/cdt/CommentManager.java
|
/*
MIT License
Copyright (c) 2018-2019 Gang ZHANG
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package depends.extractor.cpp.cdt;
import org.eclipse.cdt.core.dom.ast.IASTComment;
import org.eclipse.cdt.core.dom.ast.IASTTranslationUnit;
import org.eclipse.cdt.internal.core.dom.parser.ASTTranslationUnit;
public class CommentManager {
private IASTTranslationUnit translationUnit;
IASTComment[] comments;
boolean[] joinWithNext;
public CommentManager(IASTTranslationUnit translationUnit) {
this.translationUnit = translationUnit;
comments = ((ASTTranslationUnit) translationUnit).getComments();
joinWithNext = new boolean[comments.length];
for (int i=1;i<comments.length;i++) {
IASTComment previous = comments[i-1];
int previousEnd = (previous.getFileLocation().getNodeOffset()+
previous.getFileLocation().getNodeLength());
IASTComment current = comments[i];
if (current.getFileLocation().getNodeOffset()-previousEnd<5)
joinWithNext[i-1] = true;
else
joinWithNext[i-1] = false;
}
joinWithNext[comments.length-1] = false;
}
public String getLeadingCommentText(int startOffset) {
int adjacent = findCommentIndex(startOffset);
if (adjacent==-1) return "";
String comment = new String( comments[adjacent].getComment());
int i=adjacent-1;
while(i>=0) {
if (joinWithNext[i]) {
comment = new String(comments[i].getComment())+comment;
i--;
}else {
break;
}
}
return comment;
}
private int findCommentIndex(int startOffset) {
IASTComment[] comments = ((ASTTranslationUnit) translationUnit).getComments();
int i=0;
for (;i<comments.length;i++) {
IASTComment c = comments[i];
int gap = startOffset-(c.getFileLocation().getNodeOffset()+
c.getFileLocation().getNodeLength());
if (gap>0 && gap<10) {
break;
}
if (gap<0) return -1;
}
return i>=comments.length?-1:i;
}
}
| 2,868 | 32.360465 | 80 |
java
|
depends
|
depends-master/src/main/java/depends/extractor/cpp/cdt/ExpressionUsage.java
|
/*
MIT License
Copyright (c) 2018-2019 Gang ZHANG
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package depends.extractor.cpp.cdt;
import org.eclipse.cdt.core.dom.ast.*;
import org.eclipse.cdt.core.dom.ast.cpp.ICPPASTNewExpression;
import depends.entity.Expression;
import depends.entity.GenericName;
import depends.entity.repo.IdGenerator;
import depends.extractor.HandlerContext;
public class ExpressionUsage {
HandlerContext context;
IdGenerator idGenerator;
public ExpressionUsage(HandlerContext context,IdGenerator idGenerator) {
this.context = context;
this.idGenerator = idGenerator;
}
public void foundCallExpressionOfFunctionStyle(String functionName, IASTDeclarator declarator) {
/* create expression and link it with parent*/
Expression expression = new Expression(idGenerator.generateId());
context.lastContainer().addExpression(declarator,expression);
expression.setCall(true);
expression.setIdentifier(functionName);
}
public Expression foundExpression(IASTExpression ctx) {
Expression parent = findParentInStack(ctx);
Expression expression = null;
if (parent!=null && ctx.getParent()!=null && (ctx.getParent().getChildren().length==1)){
expression = parent;
}else {
/* create expression and link it with parent*/
expression = new Expression(idGenerator.generateId());
expression.setText(ctx.getRawSignature());
context.lastContainer().addExpression(ctx, expression);
expression.setParent(parent);
}
if (isTerminalExpression(ctx)) {
tryFillExpressionTypeAndIdentifier(ctx,expression);
return expression;
}
expression.setSet(expression.isSet() || isSet(ctx));
expression.setCall(expression.isCall() || (ctx instanceof IASTFunctionCallExpression)?true:false);
expression.setLogic(expression.isLogic() || isLogic(ctx));
if (ctx instanceof ICPPASTNewExpression){
expression.setCreate(true);;
}
expression.setDot(expression.isDot() || isDot(ctx));
/**
* | expression bop='.'
( IDENTIFIER
| methodCall
)
*/
//method call
if (ctx instanceof IASTFunctionCallExpression) {
expression.setIdentifier(getMethodCallIdentifier((IASTFunctionCallExpression)ctx));
expression.setCall(true);
}
if (ctx instanceof ICPPASTNewExpression) {
expression.setRawType(GenericName.build(ASTStringUtilExt.getTypeIdString(((ICPPASTNewExpression)ctx).getTypeId())));
expression.setCall(true);
expression.disableDriveTypeFromChild();
}
if (ctx instanceof IASTCastExpression) {
expression.setCast(true);
expression.setRawType(GenericName.build(ASTStringUtilExt.getTypeIdString(((IASTCastExpression)ctx).getTypeId())));
expression.disableDriveTypeFromChild();
}
if (expression.isDot() ) {
if (ctx instanceof IASTBinaryExpression) {
IASTExpression op2 = ((IASTBinaryExpression) ctx).getOperand2();
if (op2 instanceof IASTIdExpression)
expression.setIdentifier(ASTStringUtilExt.getName(((IASTIdExpression) op2).getName()));
else if (op2 instanceof IASTLiteralExpression)
expression.setIdentifier(ASTStringUtilExt.getName((IASTLiteralExpression) op2));
else if (op2 instanceof IASTFunctionCallExpression)
expression.setIdentifier(getMethodCallIdentifier((IASTFunctionCallExpression) op2));
}
}
return expression;
}
private boolean isTerminalExpression(IASTExpression ctx) {
if(ctx instanceof IASTIdExpression) return true;
if(ctx instanceof IASTLiteralExpression) return true;
if(ctx instanceof IASTTypeIdExpression) return true;
//TODO: add others
return false;
}
private void tryFillExpressionTypeAndIdentifier(IASTExpression ctx, Expression expression) {
//1. we only handle leaf node. if there is still expression,
// the type will be determined by child node in the expression
if (ctx instanceof IASTIdExpression){
expression.setIdentifier(ASTStringUtilExt.getName(((IASTIdExpression)ctx).getName()));
}else if (ctx instanceof IASTLiteralExpression) {
//2. if it is a var name, dertermine the type based on context.
expression.setIdentifier("<Literal>");
expression.setRawType("<Built-in>");
}else if (ctx instanceof IASTTypeIdExpression) {
//3. if given type directly
expression.setRawType(ASTStringUtilExt.getTypeIdString(((IASTTypeIdExpression)ctx).getTypeId()));
//TODO: check
}
}
private GenericName getMethodCallIdentifier(IASTFunctionCallExpression methodCall) {
IASTExpression f = methodCall.getFunctionNameExpression();
if (f instanceof IASTIdExpression) {
return GenericName.build(ASTStringUtilExt.getName(((IASTIdExpression)f).getName()));
}
if (f instanceof IASTFieldReference){
IASTFieldReference func = (IASTFieldReference) f;
return GenericName.build(ASTStringUtilExt.getName(func.getFieldName()));
}
return null;
}
private boolean isDot(IASTExpression ctx) {
if (ctx instanceof IASTBinaryExpression) {
int op = ((IASTBinaryExpression)ctx).getOperator();
if (op==IASTBinaryExpression.op_pmdot ||
op==IASTBinaryExpression.op_pmarrow ) return true;
}
if (ctx instanceof IASTFunctionCallExpression){
if (ctx.getChildren().length>0){
if (ctx.getChildren()[0] instanceof IASTFieldReference)
return true;
}
}
return false;
}
private boolean isLogic(IASTExpression ctx) {
if (ctx instanceof IASTBinaryExpression) {
int op = ((IASTBinaryExpression)ctx).getOperator();
if (op == IASTBinaryExpression.op_equals ||
op == IASTBinaryExpression.op_notequals ||
op == IASTBinaryExpression.op_lessThan ||
op == IASTBinaryExpression.op_lessEqual ||
op == IASTBinaryExpression.op_greaterThan ||
op == IASTBinaryExpression.op_greaterEqual ||
op == IASTBinaryExpression.op_logicalAnd ||
op == IASTBinaryExpression.op_logicalOr
) {
return true;
}
}
return false;
}
public boolean isSet(IASTExpression ctx) {
if (ctx instanceof IASTBinaryExpression) {
int op = ((IASTBinaryExpression)ctx).getOperator();
if (op>=IASTBinaryExpression.op_assign &&
op<=IASTBinaryExpression.op_binaryOrAssign) {
return true;
}
}
if (ctx instanceof IASTUnaryExpression) {
int op = ((IASTUnaryExpression)ctx).getOperator();
if (op == IASTUnaryExpression.op_prefixIncr ||
op == IASTUnaryExpression.op_prefixDecr ||
op == IASTUnaryExpression.op_postFixIncr ||
op == IASTUnaryExpression.op_postFixIncr
)
return true;
}
return false;
}
private Expression findParentInStack(IASTNode ctx) {
if (ctx==null) return null;
if (ctx.getParent()==null) return null;
if (context.lastContainer()==null) {
return null;
}
if (context.lastContainer().expressions().containsKey(ctx.getParent())) return context.lastContainer().expressions().get(ctx.getParent());
return findParentInStack(ctx.getParent());
}
}
| 7,799 | 35.27907 | 140 |
java
|
depends
|
depends-master/src/main/java/depends/extractor/cpp/cdt/CppVisitor.java
|
/*
MIT License
Copyright (c) 2018-2019 Gang ZHANG
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package depends.extractor.cpp.cdt;
import depends.entity.*;
import depends.entity.repo.EntityRepo;
import depends.entity.repo.IdGenerator;
import depends.extractor.cpp.CppHandlerContext;
import depends.importtypes.ExactMatchImport;
import depends.importtypes.FileImport;
import depends.importtypes.PackageWildCardImport;
import depends.relations.IBindingResolver;
import org.codehaus.plexus.util.StringUtils;
import org.eclipse.cdt.core.dom.ast.*;
import org.eclipse.cdt.core.dom.ast.IASTEnumerationSpecifier.IASTEnumerator;
import org.eclipse.cdt.core.dom.ast.cpp.*;
import org.eclipse.cdt.core.dom.ast.cpp.ICPPASTCompositeTypeSpecifier.ICPPASTBaseSpecifier;
import org.eclipse.cdt.internal.core.dom.parser.cpp.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
public class CppVisitor extends ASTVisitor {
private static final Logger logger = LoggerFactory.getLogger(CppVisitor.class);
private CppHandlerContext context;
private IdGenerator idGenerator;
private PreprocessorHandler preprocessorHandler;
IBindingResolver bindingResolver;
private ExpressionUsage expressionUsage;
HashSet<String> file;
public CppVisitor(String fileFullPath, EntityRepo entityRepo, PreprocessorHandler preprocessorHandler, IBindingResolver bindingResolver) {
super(true);
this.shouldVisitAmbiguousNodes = true;
this.shouldVisitImplicitNames = true;
this.includeInactiveNodes = true;
this.context = new CppHandlerContext(entityRepo, bindingResolver);
idGenerator = entityRepo;
this.bindingResolver = bindingResolver;
this.preprocessorHandler = preprocessorHandler;
expressionUsage = new ExpressionUsage(context,entityRepo);
file = new HashSet<>();
context.startFile(fileFullPath);
file.add(this.context.currentFile().getQualifiedName());
}
@Override
public int visit(IASTTranslationUnit tu) {
for (String incl:preprocessorHandler.getDirectIncludedFiles(tu.getAllPreprocessorStatements(),context.currentFile().getQualifiedName())) {
context.foundNewImport(new FileImport(incl));
}
MacroExtractor macroExtractor = new MacroExtractor(tu.getAllPreprocessorStatements(),context.currentFile().getQualifiedName());
macroExtractor.extract(context);
for (IASTNode child:tu.getChildren()) {
if (notLocalFile(child)) continue;
child.accept(this);
}
return ASTVisitor.PROCESS_SKIP;
}
@Override
public int visit(IASTProblem problem) {
if (notLocalFile(problem)) return ASTVisitor.PROCESS_SKIP;
System.out.println("warning: parse error " + problem.getOriginalNode().getRawSignature() + problem.getMessageWithLocation());
return super.visit(problem);
}
private boolean notLocalFile(IASTNode node) {
if (file.contains(node.getFileLocation().getFileName())) {
return false;
}
return true;
}
// PACKAGES
@Override
public int visit(ICPPASTNamespaceDefinition namespaceDefinition) {
if (notLocalFile(namespaceDefinition)) return ASTVisitor.PROCESS_SKIP;
String ns = namespaceDefinition.getName().toString().replace("::", ".");
logger.trace("enter ICPPASTNamespaceDefinition " + ns);
Entity pkg = context.foundNamespace(ns,namespaceDefinition.getFileLocation().getStartingLineNumber());
context.foundNewImport(new PackageWildCardImport(ns));
return super.visit(namespaceDefinition);
}
@Override
public int leave(ICPPASTNamespaceDefinition namespaceDefinition) {
if (notLocalFile(namespaceDefinition)) return ASTVisitor.PROCESS_SKIP;
context.exitLastedEntity();
return super.leave(namespaceDefinition);
}
// Types
@Override
public int visit(IASTDeclSpecifier declSpec) {
if (notLocalFile(declSpec)) return ASTVisitor.PROCESS_SKIP;
logger.trace("enter IASTDeclSpecifier " + declSpec.getClass().getSimpleName());
if (declSpec instanceof IASTCompositeTypeSpecifier) {
IASTCompositeTypeSpecifier type = (IASTCompositeTypeSpecifier)declSpec;
String name = ASTStringUtilExt.getName(type);
List<GenericName> param = ASTStringUtilExt.getTemplateParameters(type);
TypeEntity typeEntity = context.foundNewType(name, type.getFileLocation().getStartingLineNumber());
if (declSpec instanceof ICPPASTCompositeTypeSpecifier) {
ICPPASTBaseSpecifier[] baseSpecififers = ((ICPPASTCompositeTypeSpecifier)declSpec).getBaseSpecifiers();
for (ICPPASTBaseSpecifier baseSpecififer:baseSpecififers) {
String extendName = ASTStringUtilExt.getName(baseSpecififer.getNameSpecifier());
context.foundExtends(extendName);
}
}
}
else if (declSpec instanceof IASTEnumerationSpecifier) {
context.foundNewType(ASTStringUtilExt.getName(declSpec), declSpec.getFileLocation().getStartingLineNumber());
}else {
//we do not care other types
}
return super.visit(declSpec);
}
@Override
public int leave(IASTDeclSpecifier declSpec) {
if (notLocalFile(declSpec)) return ASTVisitor.PROCESS_SKIP;
if (declSpec instanceof IASTCompositeTypeSpecifier) {
context.exitLastedEntity();
}
else if (declSpec instanceof IASTEnumerationSpecifier) {
context.exitLastedEntity();
}else {
//we do not care other types
}
return super.leave(declSpec);
}
//Function or Methods
@Override
public int visit(IASTDeclarator declarator) {
if (notLocalFile(declarator)) return ASTVisitor.PROCESS_SKIP;
logger.trace("enter IASTDeclarator " + declarator.getClass().getSimpleName());
if (declarator instanceof IASTFunctionDeclarator){
GenericName returnType = null;
if ( declarator.getParent() instanceof IASTSimpleDeclaration) {
IASTSimpleDeclaration decl = (IASTSimpleDeclaration)(declarator.getParent());
returnType = buildGenericNameFromDeclSpecifier(decl.getDeclSpecifier());
String rawName = ASTStringUtilExt.getName(declarator);
List<Entity> namedEntity = context.currentFile().lookupFunctionInVisibleScope(GenericName.build(rawName));
if (namedEntity!=null) {
rawName = namedEntity.get(0).getQualifiedName();
}
returnType = reMapIfConstructDeconstruct(rawName,returnType);
context.foundMethodDeclaratorProto(rawName, returnType,decl.getFileLocation().getStartingLineNumber());
}
else if ( declarator.getParent() instanceof IASTFunctionDefinition) {
IASTFunctionDefinition decl = (IASTFunctionDefinition)declarator.getParent();
returnType = buildGenericNameFromDeclSpecifier(decl.getDeclSpecifier());
String rawName = ASTStringUtilExt.getName(declarator);
List<Entity> namedEntity = context.currentFile().lookupFunctionInVisibleScope(GenericName.build(rawName));
if (namedEntity!=null) {
rawName = namedEntity.get(0).getQualifiedName();
}
returnType = reMapIfConstructDeconstruct(rawName,returnType);
context.foundMethodDeclaratorImplementation(rawName, returnType,decl.getFileLocation().getStartingLineNumber());
}
}
return super.visit(declarator);
}
private GenericName buildGenericNameFromDeclSpecifier(IASTDeclSpecifier decl) {
String name = ASTStringUtilExt.getName(decl);
List<GenericName> templateParams = ASTStringUtilExt.getTemplateParameters(decl);
if (name==null)
return null;
return new GenericName(name,templateParams);
}
/**
* In case of return type is empty, it maybe a construct/deconstruct function
* @param functionname
* @param returnType
* @return
*/
private GenericName reMapIfConstructDeconstruct(String functionname, GenericName returnType) {
if (returnType!=null && returnType.uniqName().length()>0)
return returnType;
if (functionname.contains("::")) {
return new GenericName(functionname.substring(0, functionname.indexOf("::")));
}else {
return new GenericName(functionname);
}
}
@Override
public int leave(IASTDeclarator declarator) {
if (notLocalFile(declarator)) return ASTVisitor.PROCESS_SKIP;
if (declarator instanceof IASTFunctionDeclarator){
if ( declarator.getParent() instanceof IASTSimpleDeclaration) {
String rawName = ASTStringUtilExt.getName(declarator);
if (rawName.equals(context.lastContainer().getRawName().getName())) {
context.exitLastedEntity();
}else {
System.err.println("unexpected symbol");
}
}
}
return super.leave(declarator);
}
@Override
public int leave(IASTDeclaration declaration) {
if (notLocalFile(declaration)) return ASTVisitor.PROCESS_SKIP;
if ( declaration instanceof IASTFunctionDefinition) {
context.exitLastedEntity();
}
return super.leave(declaration);
}
// Variables
@Override
public int visit(IASTDeclaration declaration) {
if (notLocalFile(declaration)) return ASTVisitor.PROCESS_SKIP;
logger.trace("enter IASTDeclaration " + declaration.getClass().getSimpleName());
if (declaration instanceof ICPPASTUsingDeclaration) {
String ns = ASTStringUtilExt.getName((ICPPASTUsingDeclaration)declaration);
context.foundNewImport(new PackageWildCardImport(ns));
}
else if (declaration instanceof ICPPASTUsingDirective) {
String ns = ((ICPPASTUsingDirective)declaration).getQualifiedName().toString().replace("::", ".");
context.foundNewImport(new ExactMatchImport(ns));
}
else if (declaration instanceof IASTSimpleDeclaration ) {
for (IASTDeclarator declarator:((IASTSimpleDeclaration) declaration).getDeclarators()) {
IASTDeclSpecifier declSpecifier = ((IASTSimpleDeclaration) declaration).getDeclSpecifier();
//Found new typedef definition
if (declSpecifier.getStorageClass()==IASTDeclSpecifier.sc_typedef) {
context.foundNewAlias(ASTStringUtilExt.getName(declarator),ASTStringUtilExt.getName(declSpecifier));
}else if (!(declarator instanceof IASTFunctionDeclarator)) {
String varType = ASTStringUtilExt.getName(declSpecifier);
String varName = ASTStringUtilExt.getName(declarator);
if (!StringUtils.isEmpty(varType)) {
context.foundVarDefinition(varName, GenericName.build(varType), ASTStringUtilExt.getTemplateParameters(declSpecifier),declarator.getFileLocation().getStartingLineNumber());
}else {
expressionUsage.foundCallExpressionOfFunctionStyle(varName,declarator);
}
}
}
}else if (declaration instanceof IASTFunctionDefinition){
//handled in declarator
}else if (declaration instanceof CPPASTVisibilityLabel){
//we ignore the visibility in dependency check
}else if (declaration instanceof CPPASTLinkageSpecification){
}else if (declaration instanceof CPPASTTemplateDeclaration){
}else if (declaration instanceof CPPASTProblemDeclaration){
System.err.println("parsing error \n" + declaration.getRawSignature());
}else if (declaration instanceof ICPPASTAliasDeclaration){
IASTName name = ((ICPPASTAliasDeclaration)declaration).getAlias();
String alias = ASTStringUtilExt.getSimpleName(name).replace("::", ".");
ICPPASTTypeId mapped = ((ICPPASTAliasDeclaration)declaration).getMappingTypeId();
String originalName1 = ASTStringUtilExt.getTypeIdString(mapped);
context.foundNewAlias(alias, originalName1);
}else if (declaration instanceof CPPASTNamespaceAlias){
IASTName name = ((CPPASTNamespaceAlias)declaration).getAlias();
String alias = ASTStringUtilExt.getSimpleName(name).replace("::", ".");
IASTName mapped = ((CPPASTNamespaceAlias)declaration).getMappingName();
String originalName = ASTStringUtilExt.getName(mapped);
context.foundNewAlias(alias, originalName);
}
else if(declaration instanceof CPPASTStaticAssertionDeclaration)
{
}else if (declaration instanceof CPPASTTemplateSpecialization) {
}
else{
System.out.println("not handled type: " + declaration.getClass().getName());
System.out.println(declaration.getRawSignature());
}
return super.visit(declaration);
}
@Override
public int visit(IASTEnumerator enumerator) {
if (notLocalFile(enumerator)) return ASTVisitor.PROCESS_SKIP;
logger.trace("enter IASTEnumerator " + enumerator.getClass().getSimpleName());
VarEntity var = context.foundVarDefinition(enumerator.getName().toString(), context.currentType().getRawName(), new ArrayList<>(),enumerator.getFileLocation().getStartingLineNumber());
return super.visit(enumerator);
}
@Override
public int visit(IASTExpression expression) {
if (notLocalFile(expression)) return ASTVisitor.PROCESS_SKIP;
Expression expr = expressionUsage.foundExpression(expression);
expr.setLine(expression.getFileLocation().getStartingLineNumber());
return super.visit(expression);
}
@Override
public int visit(IASTParameterDeclaration parameterDeclaration) {
if (notLocalFile(parameterDeclaration)) return ASTVisitor.PROCESS_SKIP;
logger.trace("enter IASTParameterDeclaration " + parameterDeclaration.getClass().getSimpleName());
String parameterName = ASTStringUtilExt.getName(parameterDeclaration.getDeclarator());
String parameterType = ASTStringUtilExt.getName(parameterDeclaration.getDeclSpecifier());
if (context.currentFunction()!=null) {
VarEntity var = new VarEntity(GenericName.build(parameterName),GenericName.build(parameterType),context.currentFunction(),idGenerator.generateId());
context.currentFunction().addParameter(var );
}else {
//System.out.println("** parameterDeclaration = " + parameter);
}
return super.visit(parameterDeclaration);
}
}
| 14,262 | 41.198225 | 186 |
java
|
depends
|
depends-master/src/main/java/depends/extractor/cpp/cdt/ASTStringUtilExt.java
|
package depends.extractor.cpp.cdt;
import depends.entity.GenericName;
import depends.entity.TypeEntity;
import org.eclipse.cdt.core.dom.ast.*;
import org.eclipse.cdt.core.dom.ast.cpp.ICPPASTNameSpecifier;
import org.eclipse.cdt.core.dom.ast.cpp.ICPPASTQualifiedName;
import org.eclipse.cdt.core.dom.ast.cpp.ICPPASTUsingDeclaration;
import org.eclipse.cdt.internal.core.dom.parser.cpp.CPPASTTemplateId;
import org.eclipse.cdt.internal.core.model.ASTStringUtil;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
/**
* This extends the CDT ASTStringUtil class.
* A tricky point here is that we have to use some of the reflection mechanism to invoke
* some private functions in ASTStringUtils class
* It is not good, but it seems the most easiest one to reuse existing functions
*/
public class ASTStringUtilExt extends ASTStringUtil {
public static String getName(IASTDeclSpecifier decl) {
StringBuilder buffer = new StringBuilder();
String name = appendBareDeclSpecifierString(buffer, decl).toString().replace("::", ".").replace("...", "");
return name;
}
public static String getName(IASTLiteralExpression expr) {
return expr.getRawSignature().replace("::", ".").replace("...", "");
}
public static String getTypeIdString(IASTTypeId typeId) {
StringBuilder sb = new StringBuilder();
return appendBareTypeIdString(sb, typeId).toString().replace("::", ".");
}
/**
* retrieve template parameters from declSpecifier
*/
public static List<GenericName> getTemplateParameters(IASTDeclSpecifier declSpecifier) {
List<GenericName> parameters = new ArrayList<>();
declSpecifier.accept(new TemplateParameterASTVisitor(parameters));
return parameters;
}
private static StringBuilder appendBareDeclSpecifierString(StringBuilder buffer, IASTDeclSpecifier declSpecifier) {
if (declSpecifier instanceof IASTCompositeTypeSpecifier) {
final IASTCompositeTypeSpecifier compositeTypeSpec = (IASTCompositeTypeSpecifier) declSpecifier;
appendBareNameString(buffer, compositeTypeSpec.getName());
} else if (declSpecifier instanceof IASTElaboratedTypeSpecifier) {
final IASTElaboratedTypeSpecifier elaboratedTypeSpec = (IASTElaboratedTypeSpecifier) declSpecifier;
appendBareNameString(buffer, elaboratedTypeSpec.getName());
} else if (declSpecifier instanceof IASTEnumerationSpecifier) {
final IASTEnumerationSpecifier enumerationSpec = (IASTEnumerationSpecifier) declSpecifier;
appendBareNameString(buffer, enumerationSpec.getName());
} else if (declSpecifier instanceof IASTSimpleDeclSpecifier) {
buffer.append(TypeEntity.buildInType.getRawName());
} else if (declSpecifier instanceof IASTNamedTypeSpecifier) {
final IASTNamedTypeSpecifier namedTypeSpec = (IASTNamedTypeSpecifier) declSpecifier;
appendBareNameString(buffer, namedTypeSpec.getName());
}
return buffer;
}
private static StringBuilder appendBareNameString(StringBuilder buffer, IASTName name) {
if (name instanceof ICPPASTQualifiedName) {
final ICPPASTQualifiedName qualifiedName = (ICPPASTQualifiedName) name;
final ICPPASTNameSpecifier[] segments = qualifiedName.getAllSegments();
for (int i = 0; i < segments.length; i++) {
if (i > 0) {
buffer.append(".");
}
appendQualifiedNameStringWithReflection(buffer, segments[i]);
}
} else if (name instanceof CPPASTTemplateId) {
appendQualifiedNameStringWithReflection(buffer,(CPPASTTemplateId)name);
} else if (name != null) {
buffer.append(name.getSimpleID());
}
return buffer;
}
private static void appendQualifiedNameStringWithReflection(StringBuilder buffer, IASTName name) {
try {
Method m = ASTStringUtil.class.getDeclaredMethod("appendQualifiedNameString", StringBuilder.class,
IASTName.class);
m.setAccessible(true); // if security settings allow this
m.invoke(null, buffer, name); // use null if the method is static
} catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException
| InvocationTargetException e) {
System.err.println("Error: cannot invoke ASTStringUtils method of <appendQualifiedNameString>");
}
}
private static void appendQualifiedNameStringWithReflection(StringBuilder buffer,
CPPASTTemplateId templateId) {
appendQualifiedNameStringWithReflection(buffer,templateId.getTemplateName());
}
private static void appendQualifiedNameStringWithReflection(StringBuilder buffer,
ICPPASTNameSpecifier nameSpecifier) {
if (nameSpecifier instanceof CPPASTTemplateId) {
appendQualifiedNameStringWithReflection(buffer,(CPPASTTemplateId)nameSpecifier);
return;
}
try {
Method m = ASTStringUtil.class.getDeclaredMethod("appendQualifiedNameString", StringBuilder.class,
ICPPASTNameSpecifier.class);
m.setAccessible(true); // if security settings allow this
m.invoke(null, buffer, nameSpecifier); // use null if the method is static
} catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException
| InvocationTargetException e) {
System.err.println("Error: cannot invoke ASTStringUtils method of <appendQualifiedNameString>");
}
}
private static StringBuilder appendBareTypeIdString(StringBuilder buffer, IASTTypeId typeId) {
return appendBareDeclSpecifierString(buffer, typeId.getDeclSpecifier());
}
public static String getName(IASTDeclarator declarator) {
return declarator.getName().toString().replace("::", ".");
}
public static String getName(ICPPASTUsingDeclaration declaration) {
return declaration.getName().toString().replace("::", ".");
}
public static String getName(IASTName name) {
return name.getRawSignature().toString().replace("::", ".");
}
private static StringBuilder appendBareNameString(StringBuilder buffer, ICPPASTNameSpecifier name) {
if (name instanceof ICPPASTQualifiedName) {
final ICPPASTQualifiedName qualifiedName = (ICPPASTQualifiedName) name;
final ICPPASTNameSpecifier[] segments = qualifiedName.getAllSegments();
for (int i = 0; i < segments.length; i++) {
if (i > 0) {
buffer.append(".");
}
appendQualifiedNameStringWithReflection(buffer, segments[i]);
}
} else if (name instanceof CPPASTTemplateId) {
appendQualifiedNameStringWithReflection(buffer,(CPPASTTemplateId)name);
} else if (name != null) {
buffer.append(name.getRawSignature());
}
return buffer;
}
public static String getName(ICPPASTNameSpecifier nameSpecifier) {
StringBuilder buffer = new StringBuilder();
String name = appendBareNameString(buffer, nameSpecifier).toString().replace("::", ".").replace("...", "");
return name;
}
}
| 6,701 | 38.656805 | 116 |
java
|
depends
|
depends-master/src/main/java/depends/extractor/cpp/cdt/PreprocessorHandler.java
|
/*
MIT License
Copyright (c) 2018-2019 Gang ZHANG
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package depends.extractor.cpp.cdt;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import org.eclipse.cdt.core.dom.ast.IASTFileLocation;
import org.eclipse.cdt.core.dom.ast.IASTPreprocessorIncludeStatement;
import org.eclipse.cdt.core.dom.ast.IASTPreprocessorStatement;
import org.eclipse.cdt.internal.core.parser.scanner.ScannerUtility;
import multilang.depends.util.file.FileTraversal;
import multilang.depends.util.file.FileTraversal.IFileVisitor;
import multilang.depends.util.file.FileUtil;
public class PreprocessorHandler {
private List<String> includePaths;
private String inputSrcPath;
private HashSet<String> allFiles = new HashSet<>();
public PreprocessorHandler(String inputSrcPath, List<String> includePaths){
this.inputSrcPath = inputSrcPath;
this.includePaths = includePaths;
buildAllFiles();
}
class AllFileVisitor implements IFileVisitor{
@Override
public void visit(File file) {
try {
allFiles.add(file.getCanonicalPath());
} catch (IOException e) {
}
}
}
private void buildAllFiles() {
allFiles = new HashSet<>();
AllFileVisitor v = new AllFileVisitor();
if (inputSrcPath!=null) {
FileTraversal ft = new FileTraversal(v,false,true);
ft.travers(inputSrcPath);
}
for (String includePath:includePaths) {
FileTraversal ft = new FileTraversal(v,false,true);
ft.travers(includePath);
}
}
private boolean existFile(String checkPath) {
checkPath = FileUtil.uniformPath(checkPath);
return allFiles.contains(checkPath);
}
public List<String> getDirectIncludedFiles(IASTPreprocessorStatement[] statements, String fileLocation) {
ArrayList<String> includedFullPathNames = new ArrayList<>();
for (int statementIndex=0;statementIndex<statements.length;statementIndex++) {
if (statements[statementIndex] instanceof IASTPreprocessorIncludeStatement)
{
IASTPreprocessorIncludeStatement incl = (IASTPreprocessorIncludeStatement)(statements[statementIndex]);
if (!incl.getFileLocation().getFileName().equals(fileLocation))
continue;
String path = resolveInclude(incl);
if (!existFile(path)) {
continue;
}
if (FileUtil.isDirectory(path)) {
continue;
}
includedFullPathNames.add(path);
}
}
return includedFullPathNames;
}
private String resolveInclude(IASTPreprocessorIncludeStatement incl) {
String path = incl.toString();
int pos = path.indexOf(' ');
path = path.substring(pos+1).trim();
if (path.startsWith("\"") || path.startsWith("<")){
path = path.substring(1);
path = path.substring(0,path.length()-1);
}
//First search in local directory
IASTFileLocation location = incl.getFileLocation();
String locationDir = FileUtil.getLocatedDir(location.getFileName());
ArrayList<String> searchPath = new ArrayList<>();
searchPath.add(locationDir);
searchPath.addAll(includePaths);
for (String includePath:searchPath) {
String checkPath = ScannerUtility.createReconciledPath(includePath,path);
if (existFile(checkPath)) {
return FileUtil.uniqFilePath(checkPath);
}
}
return "";
}
public List<String> getIncludePaths() {
return includePaths;
}
}
| 4,292 | 32.80315 | 107 |
java
|
depends
|
depends-master/src/main/java/depends/extractor/cpp/cdt/CDTParser.java
|
/*
MIT License
Copyright (c) 2018-2019 Gang ZHANG
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package depends.extractor.cpp.cdt;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.eclipse.cdt.core.dom.ast.IASTTranslationUnit;
import org.eclipse.cdt.core.parser.IScanner;
import org.eclipse.cdt.core.parser.NullLogService;
import org.eclipse.cdt.core.parser.ParserMode;
import org.eclipse.cdt.internal.core.dom.parser.AbstractGNUSourceCodeParser;
import org.eclipse.cdt.internal.core.dom.parser.c.CASTTranslationUnit;
import org.eclipse.cdt.internal.core.dom.parser.cpp.GNUCPPSourceParser;
import depends.extractor.cpp.Scanner;
@SuppressWarnings("deprecation")
public class CDTParser {
NullLogService NULL_LOG = new NullLogService();
protected Map<String, String> macroMap ;
protected List<String> sysIncludePath = new ArrayList<>();
public CDTParser() {
}
public CDTParser(List<String> includesPath) {
this.sysIncludePath = includesPath;
}
public IASTTranslationUnit parse(String file, Map<String, String> macroMap ) {
try {
this.macroMap = macroMap;
return getTranslationUnitofCPP(file);
} catch (IOException e) {
}
return new CASTTranslationUnit();
}
public IASTTranslationUnit getTranslationUnitofCPP(String file) throws IOException {
IScanner scanner = Scanner.buildScanner(file,macroMap,sysIncludePath,false);
if (scanner==null) return null;
AbstractGNUSourceCodeParser sourceCodeParser = new GNUCPPSourceParser(
scanner, ParserMode.COMPLETE_PARSE, new NullLogService(),
new GPPParserExtensionConfigurationExtension(), null);
IASTTranslationUnit tu = sourceCodeParser.parse();
return tu;
}
}
| 2,721 | 32.604938 | 85 |
java
|
depends
|
depends-master/src/main/java/depends/extractor/cpp/cdt/GPPParserExtensionConfigurationExtension.java
|
/*
MIT License
Copyright (c) 2018-2019 Gang ZHANG
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package depends.extractor.cpp.cdt;
import org.eclipse.cdt.core.dom.parser.cpp.GPPParserExtensionConfiguration;
public class GPPParserExtensionConfigurationExtension extends GPPParserExtensionConfiguration {
@Override
public boolean supportKnRC() {
return false;
}
@Override
public boolean supportParameterInfoBlock() {
return false;
}
@Override
public boolean supportStatementsInExpressions() {
return false;
}
}
| 1,516 | 30.604167 | 95 |
java
|
depends
|
depends-master/src/main/java/depends/extractor/cpp/cdt/ANSICParserExtensionConfigurationExtension.java
|
/*
MIT License
Copyright (c) 2018-2019 Gang ZHANG
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package depends.extractor.cpp.cdt;
import org.eclipse.cdt.core.dom.parser.c.ANSICParserExtensionConfiguration;
class ANSICParserExtensionConfigurationExtension extends ANSICParserExtensionConfiguration {
@Override
public boolean supportDeclspecSpecifiers() {
return false;
}
@Override
public boolean supportKnRC() {
return false;
}
@Override
public boolean supportStatementsInExpressions() {
return false;
}
}
| 1,511 | 31.170213 | 92 |
java
|
depends
|
depends-master/src/main/java/depends/extractor/cpp/cdt/FileCache.java
|
package depends.extractor.cpp.cdt;
import java.util.HashMap;
import org.eclipse.cdt.core.index.IIndexFileLocation;
import org.eclipse.cdt.internal.core.parser.scanner.InternalFileContent;
public class FileCache {
private HashMap<String, InternalFileContent> cache;
private HashMap<IIndexFileLocation, InternalFileContent> cache2;
private FileCache() {
this.cache = new HashMap<>();
}
static FileCache inst = null;
public static FileCache getInstance() {
if (inst==null) inst = new FileCache();
return inst;
}
public InternalFileContent get(String filePath) {
InternalFileContent result = cache.get(filePath);
return result;
}
public void put(String filePath, InternalFileContent c) {
cache.put(filePath,c);
}
public InternalFileContent get(IIndexFileLocation ifl) {
InternalFileContent result = cache2.get(ifl);
return result;
}
public void put(IIndexFileLocation ifl, InternalFileContent c) {
cache2.put(ifl,c);
}
}
| 954 | 26.285714 | 72 |
java
|
depends
|
depends-master/src/main/java/depends/extractor/cpp/cdt/TemplateParameterASTVisitor.java
|
package depends.extractor.cpp.cdt;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.cdt.core.dom.ast.ASTVisitor;
import org.eclipse.cdt.core.dom.ast.IASTDeclSpecifier;
import org.eclipse.cdt.core.dom.ast.IASTIdExpression;
import org.eclipse.cdt.core.dom.ast.IASTLiteralExpression;
import org.eclipse.cdt.core.dom.ast.IASTName;
import org.eclipse.cdt.core.dom.ast.IASTNode;
import org.eclipse.cdt.core.dom.ast.IASTTypeId;
import org.eclipse.cdt.core.dom.ast.cpp.ICPPASTTemplateParameter;
import org.eclipse.cdt.internal.core.dom.parser.cpp.CPPASTTemplateId;
import depends.entity.GenericName;
class TemplateParameterASTVisitor extends ASTVisitor{
private List<GenericName> parameters;
public TemplateParameterASTVisitor(List<GenericName> parameters) {
super(true);
this.parameters = parameters;
}
@Override
public int visit(IASTName name) {
if (name instanceof CPPASTTemplateId) {
final CPPASTTemplateId templateId = (CPPASTTemplateId) name;
for (IASTNode argument:templateId.getTemplateArguments()) {
if (argument instanceof IASTTypeId) {
IASTDeclSpecifier decl = ((IASTTypeId) argument).getDeclSpecifier();
String parameterName = ASTStringUtilExt.getName(decl);
parameterName = parameterName.replace("...", "");
parameters.add(GenericName.build(parameterName));
} else if (argument instanceof IASTIdExpression){
String parameterName = ASTStringUtilExt.getName(((IASTIdExpression)argument).getName());
parameters.add(GenericName.build(parameterName));
} else if (argument instanceof IASTLiteralExpression){
parameters.add(GenericName.build("<Literal>"));
}else {
System.err.println ("TODO: unknown template arguments");
}
} }
return super.visit(name);
}
@Override
public int visit(ICPPASTTemplateParameter templateParameter) {
return super.visit(templateParameter);
}
}
| 1,896 | 31.152542 | 93 |
java
|
depends
|
depends-master/src/main/java/depends/extractor/cpp/cdt/CdtCppFileParser.java
|
/*
MIT License
Copyright (c) 2018-2019 Gang ZHANG
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package depends.extractor.cpp.cdt;
import depends.entity.repo.EntityRepo;
import depends.extractor.cpp.CppFileParser;
import depends.extractor.cpp.MacroRepo;
import depends.relations.IBindingResolver;
import org.eclipse.cdt.core.dom.ast.IASTTranslationUnit;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
public class CdtCppFileParser extends CppFileParser {
private PreprocessorHandler preprocessorHandler ;
private IBindingResolver bindingResolver;
private MacroRepo macroRepo;
public CdtCppFileParser(EntityRepo entityRepo, PreprocessorHandler preprocessorHandler, IBindingResolver bindingResolver, MacroRepo macroRepo) {
super(entityRepo);
this.preprocessorHandler = preprocessorHandler;
this.bindingResolver = bindingResolver;
this.macroRepo= macroRepo;
}
@Override
protected void parseFile(String fileFullPath) throws IOException {
Map<String, String> macroMap = new HashMap<>(macroRepo.getDefaultMap());
parse(fileFullPath,macroMap);
}
/**
*
* @param isInScope whether the parse is invoked by project file or an 'indirect' included file
* @return
*/
public void parse(String fileFullPath,Map<String, String> macroMap) throws IOException {
CppVisitor bridge = new CppVisitor(fileFullPath, entityRepo, preprocessorHandler, bindingResolver);
IASTTranslationUnit tu = (new CDTParser(preprocessorHandler.getIncludePaths())).parse(fileFullPath,macroMap);
boolean containsIncludes = false;
for (String incl:preprocessorHandler.getDirectIncludedFiles(tu.getAllPreprocessorStatements(),fileFullPath)) {
CdtCppFileParser importedParser = new CdtCppFileParser(entityRepo, preprocessorHandler, bindingResolver,macroRepo);
importedParser.parse(incl);
Map<String, String> macros = macroRepo.get(incl);
if (macros!=null)
macroMap.putAll(macros);
containsIncludes = true;
}
if (containsIncludes) {
tu = (new CDTParser(preprocessorHandler.getIncludePaths())).parse(fileFullPath,macroMap);
}
macroRepo.putMacros(fileFullPath,macroMap,tu.getMacroDefinitions());
tu.accept(bridge);
return;
}
@Override
protected boolean isPhase2Files(String fileFullPath) {
if (fileFullPath.endsWith(".h") || fileFullPath.endsWith(".hh") || fileFullPath.endsWith(".hpp")
|| fileFullPath.endsWith(".hxx"))
return true;
return false;
}
}
| 3,411 | 38.218391 | 145 |
java
|
depends
|
depends-master/src/main/java/depends/extractor/python/PythonBuiltInType.java
|
package depends.extractor.python;
import depends.entity.FunctionCall;
import depends.entity.FunctionEntity;
import depends.entity.GenericName;
import depends.entity.TypeEntity;
import depends.entity.repo.BuiltInType;
import depends.relations.FunctionMatcher;
import java.util.ArrayList;
import java.util.List;
public class PythonBuiltInType extends BuiltInType {
public static final String PACKAGE_PY_NAME = "__init__.py";
public static String[] BUILT_IN_FUNCTIONS = { "abs", "delattr", "hash", "memoryview", "set", "all", "dict", "help",
"min", "setattr", "any", "dir", "hex", "next", "slice", "exit", "ascii", "divmod", "id", "object", "sorted",
"bin", "enumerate", "input", "oct", "staticmethod", "bool", "eval", "int", "open", "str", "breakpoint",
"exec", "isinstance", "ord", "sum", "bytearray", "filter", "issubclass", "pow", "super", "bytes", "float",
"iter", "print", "tuple", "callable", "format", "len", "property", "type", "chr", "frozenset", "list",
"range", "vars", "classmethod", "getattr", "locals", "repr", "zip", "compile", "globals", "map", "reversed",
"__import__", "complex", "hasattr", "max", "round" };
/**
* methods of built-in String
*/
public static String[] BUILT_IN_STRING_METHODS = { "capitalize", "center", "casefold", "count", "endswith",
"expandtabs", "encode", "find", "format", "index", "isalnum", "isalpha", "isdecimal", "isdigit",
"isidentifier", "islower", "isnumeric", "isprintable", "isspace", "istitle", "isupper", "join", "ljust",
"rjust", "lower", "upper", "swapcase", "lstrip", "rstrip", "strip", "partition", "maketrans", "rpartition",
"translate", "replace", "rfind", "rindex", "split", "rsplit", "splitlines", "startswith", "title", "zfill",
"format_map" };
/**
* methods of built-in List
*/
public static String[] BUILT_IN_LIST_METHODS = { "index", "append", "extend", "insert", "remove", "count", "pop",
"reverse", "sort", "copy", "clear" };
/**
* methods of built-in Tuple
*/
public static String[] BUILT_IN_TUPLE_METHODS = { "index", "count" };
/**
* methods of built-in Dict
*/
public static String[] BUILT_IN_DICT_METHODS = { "clear", "copy", "fromkeys", "get", "items", "keys", "popitem",
"setdefault", "pop", "values", "update", };
/**
* methods of built-in Set
*/
public static String[] BUILT_IN_SET_METHODS = { "remove", "add", "copy", "clear", "difference", "difference_update",
"discard", "intersection", "intersection_update", "isdisjoint", "issubset", "pop", "symmetric_difference",
"symmetric_difference_update", "union", "update" };
/**
* methods of built-in File
*/
public static String[] BUILT_IN_FILE_METHOD = { "close", "flush", "fileno", "isatty", "next", "read", "readline",
"readlines", "seek", "tell", "truncate", "write", "writelines" };
List<TypeEntity> buildInTypes = new ArrayList<>();
public PythonBuiltInType() {
addBuildInType(BUILT_IN_FILE_METHOD);
addBuildInType(BUILT_IN_SET_METHODS);
addBuildInType(BUILT_IN_DICT_METHODS);
addBuildInType(BUILT_IN_TUPLE_METHODS);
addBuildInType(BUILT_IN_LIST_METHODS);
addBuildInType(BUILT_IN_STRING_METHODS);
}
private void addBuildInType(String[] methods) {
TypeEntity type = new TypeEntity();
for (String method:methods) {
FunctionEntity func = new FunctionEntity(GenericName.build(method),type,-1,GenericName.build(""));
type.addFunction(func);
}
buildInTypes.add(type);
}
@Override
public boolean isBuildInTypeMethods(List<FunctionCall> functionCalls) {
for (TypeEntity type:buildInTypes) {
FunctionMatcher functionMatcher = new FunctionMatcher(type.getFunctions());
if (functionMatcher.containsAll(functionCalls)) {
return true;
}
}
return false;
}
}
| 3,738 | 37.153061 | 119 |
java
|
depends
|
depends-master/src/main/java/depends/extractor/python/PythonImportLookupStrategy.java
|
package depends.extractor.python;
import depends.entity.Entity;
import depends.entity.FileEntity;
import depends.entity.repo.EntityRepo;
import depends.extractor.UnsolvedBindings;
import depends.importtypes.FileImport;
import depends.importtypes.Import;
import depends.relations.ImportLookupStrategy;
import org.apache.commons.collections4.CollectionUtils;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.function.Predicate;
import java.util.stream.Collectors;
public class PythonImportLookupStrategy extends ImportLookupStrategy {
public PythonImportLookupStrategy(EntityRepo repo) {
super(repo);
}
@Override
public Entity lookupImportedType(String name, FileEntity fileEntity) {
List<Import> importedNames = fileEntity.getImportedNames();
for (Import importedItem:importedNames) {
if (importedItem instanceof NameAliasImport) {
NameAliasImport nameAliasImport = (NameAliasImport)importedItem;
if (name.equals(nameAliasImport.getAlias())) {
return nameAliasImport.getEntity();
}
}
}
return null;
}
@Override
public Collection<Entity> getImportedRelationEntities(List<Import> importedNames) {
Collection<Entity> files = getImportedFiles(importedNames);
Collection<Entity> filescontainsTypes = this.getImportedTypes(importedNames, new HashSet<>()).stream().map(e->{
return e.getAncestorOfType(FileEntity.class);
}).filter(new Predicate<Entity>() {
@Override
public boolean test(Entity t) {
return t!=null;
}
}).collect(Collectors.toSet());
return CollectionUtils.union(files, filescontainsTypes);
}
@Override
public Collection<Entity> getImportedTypes(List<Import> importedNames, Set<UnsolvedBindings> unsolvedBindings) {
Set<Entity> result = new HashSet<>();
for (Import importedItem:importedNames) {
if (importedItem instanceof NameAliasImport) {
NameAliasImport nameAliasImport = (NameAliasImport)importedItem;
Entity imported = nameAliasImport.getEntity();
if (imported==null) {
unsolvedBindings.add(new UnsolvedBindings(importedItem.getContent(),null));
continue;
}
result.add(imported);
}
if (importedItem instanceof FileImport) {
FileImport fileImport = (FileImport)importedItem;
Entity imported = (repo.getEntity(fileImport.getContent()));
if (imported!=null) {
result.add(imported);
}
}
}
return result;
}
@Override
public Collection<Entity> getImportedFiles(List<Import> importedNames) {
Set<Entity> files = new HashSet<>();
Collection<Entity> entities = getImportedTypes(importedNames,new HashSet<>());
for (Entity entity:entities) {
if (entity instanceof FileEntity)
files.add(entity);
else
files.add(entity.getAncestorOfType(FileEntity.class));
}
return files;
}
@Override
public boolean supportGlobalNameLookup() {
return false;
}
}
| 2,909 | 28.693878 | 113 |
java
|
depends
|
depends-master/src/main/java/depends/extractor/python/NameAliasImport.java
|
package depends.extractor.python;
import depends.entity.Entity;
import depends.importtypes.Import;
public class NameAliasImport extends Import {
private String aliasedName;
private Entity entity;
public NameAliasImport(String importedName, Entity entity,String aliasedName) {
super(importedName);
this.aliasedName = aliasedName;
this.entity = entity;
}
public Entity getEntity() {
return entity;
}
public String getAlias() {
return aliasedName;
}
}
| 473 | 17.96 | 80 |
java
|
depends
|
depends-master/src/main/java/depends/extractor/python/PythonHandlerContext.java
|
package depends.extractor.python;
import depends.entity.*;
import depends.entity.repo.EntityRepo;
import depends.extractor.HandlerContext;
import depends.relations.IBindingResolver;
public class PythonHandlerContext extends HandlerContext {
public PythonHandlerContext(EntityRepo entityRepo, IBindingResolver bindingResolver) {
super(entityRepo, bindingResolver);
}
@Override
public void addToRepo(Entity entity) {
super.addToRepo(entity);
postProcessingOfInit(entity);
}
private void postProcessingOfInit(Entity entity) {
Entity parent = entity.getParent();
if (parent == null)
return;
if (parent.getRawName().getName().endsWith(PythonBuiltInType.PACKAGE_PY_NAME)) {
Entity packageEntity = parent.getAncestorOfType(PackageEntity.class);
if (packageEntity == null)
return;
packageEntity.addChild(entity);
}
}
@Override
public AliasEntity foundNewAlias(String aliasName, String originalName) {
AliasEntity alias = super.foundNewAlias(aliasName, originalName);
if (alias != null) {
alias.setDeepResolve(true);
}
return alias;
}
@Override
public AliasEntity foundNewAlias(GenericName aliasName, Entity referToEntity) {
AliasEntity alias = super.foundNewAlias(aliasName, referToEntity);
if (alias != null) {
alias.setDeepResolve(true);
}
return alias;
}
public FileEntity startFile(String fileName) {
return super.startFile(true, fileName);
}
}
| 1,418 | 25.277778 | 87 |
java
|
depends
|
depends-master/src/main/java/depends/extractor/python/BasePythonProcessor.java
|
package depends.extractor.python;
import depends.entity.repo.BuiltInType;
import depends.extractor.AbstractLangProcessor;
import depends.relations.ImportLookupStrategy;
import java.util.ArrayList;
import java.util.List;
import static depends.deptypes.DependencyType.*;
public abstract class BasePythonProcessor extends AbstractLangProcessor{
private PythonImportLookupStrategy importedLookupStrategy;
@Override
public String[] fileSuffixes() {
return new String[] {".py"};
}
@Override
public ImportLookupStrategy getImportLookupStrategy() {
importedLookupStrategy = new PythonImportLookupStrategy(entityRepo);
return this.importedLookupStrategy;
}
@Override
public BuiltInType getBuiltInType() {
return new PythonBuiltInType();
}
@Override
public List<String> supportedRelations() {
/* To be check: is python support implemenent?
* should no cast supported.
* */
// depedencyTypes.add(IMPLEMENT);
// depedencyTypes.add(CAST);
ArrayList<String> depedencyTypes = new ArrayList<>();
depedencyTypes.add(ANNOTATION);
depedencyTypes.add(IMPORT);
depedencyTypes.add(CONTAIN);
depedencyTypes.add(INHERIT);
depedencyTypes.add(CALL);
depedencyTypes.add(PARAMETER);
depedencyTypes.add(RETURN);
depedencyTypes.add(SET);
depedencyTypes.add(CREATE);
depedencyTypes.add(USE);
depedencyTypes.add(THROW);
depedencyTypes.add(LINK);
return depedencyTypes;
}
@Override
public boolean supportCallAsImpl() {
return true;
}
}
| 1,479 | 23.262295 | 72 |
java
|
depends
|
depends-master/src/main/java/depends/extractor/python/union/PythonCodeListener.java
|
package depends.extractor.python.union;
import depends.entity.*;
import depends.entity.repo.EntityRepo;
import depends.extractor.python.NameAliasImport;
import depends.extractor.python.PythonBuiltInType;
import depends.extractor.python.PythonHandlerContext;
import depends.extractor.python.PythonParser.*;
import depends.extractor.python.PythonParserBaseListener;
import depends.extractor.IncludedFileLocator;
import depends.importtypes.FileImport;
import depends.relations.IBindingResolver;
import multilang.depends.util.file.FileUtil;
import org.antlr.v4.runtime.ParserRuleContext;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class PythonCodeListener extends PythonParserBaseListener{
private final PythonHandlerContext context;
// @Override
// public void exitEveryRule(ParserRuleContext ctx) {
// System.out.println(ctx.getClass().getSimpleName().replace("Context","")+":"+ctx.getText());
// super.exitEveryRule(ctx);
// }
private final ExpressionUsage expressionUsage;
private final EntityRepo entityRepo;
private final IncludedFileLocator includeFileLocator;
private final PythonProcessor pythonProcessor;
private final IBindingResolver bindingResolver;
public PythonCodeListener(String fileFullPath, EntityRepo entityRepo, IBindingResolver bindingResolver,
IncludedFileLocator includeFileLocator, PythonProcessor pythonProcessor) {
this.context = new PythonHandlerContext(entityRepo, bindingResolver);
this.expressionUsage = new ExpressionUsage(context, entityRepo, bindingResolver);
FileEntity fileEntity = context.startFile(fileFullPath);
this.entityRepo = entityRepo;
this.includeFileLocator = includeFileLocator;
this.bindingResolver = bindingResolver;
this.pythonProcessor = pythonProcessor;
String dir = FileUtil.uniqFilePath(FileUtil.getLocatedDir(fileFullPath));
if (entityRepo.getEntity(dir) == null) {
PackageEntity pacakgeEntity = new PackageEntity(dir, entityRepo.generateId());
entityRepo.add(pacakgeEntity);
}
PackageEntity packageEntity = (PackageEntity) entityRepo.getEntity(dir);
String moduleName = fileEntity.getRawName().uniqName().substring(packageEntity.getRawName().uniqName().length() + 1);
if (moduleName.endsWith(".py"))
moduleName = moduleName.substring(0, moduleName.length() - ".py".length());
if (fileEntity.getRawName().uniqName().endsWith(PythonBuiltInType.PACKAGE_PY_NAME)){
moduleName = "";
}
fileEntity.setModuleName(moduleName);
Entity.setParent(fileEntity, packageEntity);
packageEntity.addChild(FileUtil.getShortFileName(fileEntity.getRawName().uniqName()).replace(".py", ""), fileEntity);
}
@Override
public void enterImport_stmt(Import_stmtContext ctx) {
String moduleName = null;
for(Dotted_as_nameContext dotted_as_name:ctx.dotted_as_names().dotted_as_name()){
moduleName = getName(dotted_as_name.dotted_name());
String aliasName = moduleName;
if (dotted_as_name.name()!=null) {
aliasName = dotted_as_name.name().getText();
}
List<String> fullNames = sureImportedModulesParsed(0,moduleName,null);
for (String fullName:fullNames) {
if (FileUtil.existFile(fullName) && !(FileUtil.isDirectory(fullName))) {
context.foundNewImport(new FileImport(fullName));
}
context.foundNewImport(new NameAliasImport(fullName, entityRepo.getEntity(fullName), aliasName));
}
}
super.enterImport_stmt(ctx);
}
@Override
public void enterFrom_stmt(From_stmtContext ctx) {
String fromName = null;
if (ctx.dotted_name() != null) {
fromName = ctx.dotted_name().getText();
}
int prefixDotCount = getDotCounter(ctx);
List<String> moduleNames = getModuleNames(ctx.import_as_names());
List<String> fullNames = sureImportedModulesParsed(prefixDotCount, fromName,moduleNames);
for (String fullName:fullNames) {
if (ctx.import_as_names() == null) {// import *
ContainerEntity moduleEntity = (ContainerEntity) (entityRepo.getEntity(fullName));
if (moduleEntity != null) {
for (Entity child:moduleEntity.getChildren()) {
context.foundNewImport(new NameAliasImport(fullName, child, child.getRawName().uniqName()));
context.foundNewAlias(child.getRawName(), child);
}
if (moduleEntity instanceof PackageEntity) {
for (Entity file : moduleEntity.getChildren()) {
if (file instanceof FileEntity) {
String fileName = file.getRawName().uniqName().substring(fullName.length());
context.foundNewImport(new NameAliasImport(file.getRawName().uniqName(), file, fileName));
context.foundNewAlias(GenericName.build(FileUtil.getShortFileName(fileName).replace(".py", "")), file);
}else {
context.foundNewImport(new NameAliasImport(file.getRawName().uniqName(), file, file.getRawName().uniqName()));
context.foundNewAlias(GenericName.build(FileUtil.getShortFileName(file.getRawName().uniqName())), file);
}
}
}
if (moduleEntity instanceof FileEntity) {
String fileName = moduleEntity.getRawName().uniqName().substring(fullName.length());
context.foundNewImport(new NameAliasImport(moduleEntity.getRawName().uniqName(), moduleEntity, fileName));
}
}
} else {
for (Import_as_nameContext item : ctx.import_as_names().import_as_name()) {
String name = item.name(0).getText();
String alias = name;
if (item.name().size() > 1)
alias = item.name(1).getText();
if (FileUtil.isDirectory(fullName)) {
String fileName = fullName + File.separator + name + ".py";
if (FileUtil.existFile(fileName) && !(FileUtil.isDirectory(fileName))) {
context.foundNewImport(new FileImport(fileName));
}
}else if (FileUtil.existFile(fullName)) {
context.foundNewImport(new FileImport(fullName));
}
Entity itemEntity = bindingResolver.resolveName(entityRepo.getEntity(fullName), GenericName.build(name), true);
if (itemEntity != null) {
context.foundNewAlias(GenericName.build(alias), itemEntity);
context.foundNewImport(new NameAliasImport(itemEntity.getQualifiedName(), itemEntity, alias));
}
}
}
}
super.enterFrom_stmt(ctx);
}
private List<String> getModuleNames(Import_as_namesContext import_as_names) {
List<String> names = new ArrayList<>();
if (import_as_names==null)
return names;
for (Import_as_nameContext item : import_as_names.import_as_name()) {
String name = item.name(0).getText();
names.add(name);
}
return names;
}
private int getDotCounter(From_stmtContext ctx) {
int total = 0;
if (ctx.DOT()!=null){
total = ctx.DOT().size();
}
if (ctx.ELLIPSIS()!=null) {
total += ctx.ELLIPSIS().size()*3;
}
return total;
}
private List<String> sureImportedModulesParsed(int prefixDotCount, String fromName, List<String> moduleNames) {
ArrayList<String> visitedFiles = new ArrayList<>();
/* compute prefix path */
String dir = FileUtil.getLocatedDir(context.currentFile().getRawName().uniqName());
String preFix = "";
for (int i = 0; i < prefixDotCount - 1; i++) {
preFix = preFix + ".." + File.separator;
}
dir = dir + File.separator + preFix;
/* compute importedName */
String importedName = "";
if (fromName!=null) {
importedName = fromName.replace(".", File.separator);
}
/* search importedName from all included paths */
String uniqFrom = includeFileLocator.uniqFileName(dir, importedName);
if (uniqFrom==null)
uniqFrom = includeFileLocator.uniqFileName(dir,importedName+".py");
if (uniqFrom==null){ //cannot find the path
return visitedFiles;
}
if (uniqFrom.endsWith(".py")){
return visitIncludedFile(uniqFrom);
}
if (moduleNames!=null && moduleNames.size()>0){
for (String moduleName:moduleNames){
String fileName = uniqFrom + File.separator + moduleName;
if (!FileUtil.existFile(fileName)){
fileName +=".py";
}else if (FileUtil.isDirectory(fileName)){
fileName += File.separator + PythonBuiltInType.PACKAGE_PY_NAME;
}
List<String> files = visitIncludedFile(fileName);
visitedFiles.addAll(files);
}
}else{
return visitIncludedFile(uniqFrom);
}
return visitedFiles;
}
private List<String> visitIncludedFile(String fullName) {
List<String> visitedFiles = new ArrayList<>();
if (FileUtil.isDirectory(fullName)){
File d = new File(fullName);
File[] files = d.listFiles();
for (File file : files) {
if (!file.isDirectory()) {
if (file.getAbsolutePath().endsWith(".py")) {
String fileName = FileUtil.uniqFilePath(file.getAbsolutePath());
visitIncludedFile(fileName);
visitedFiles.add(fileName);
}
}
}
if (FileUtil.existFile(fullName+File.separator + PythonBuiltInType.PACKAGE_PY_NAME)) {
visitedFiles.add( fullName+File.separator +PythonBuiltInType.PACKAGE_PY_NAME);
}
}else{
invokeParser(fullName);
visitedFiles.add(fullName);
}
return visitedFiles;
}
private void invokeParser(String fileName){
PythonFileParser importedParser = new PythonFileParser(entityRepo, includeFileLocator, bindingResolver,
pythonProcessor);
try {
importedParser.parse(fileName);
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void enterFuncdef(FuncdefContext ctx) {
String functionName ="<empty>";
String name = getName(ctx.name());
if (name!=null) {
functionName = name;
}
FunctionEntity method = context.foundMethodDeclarator(functionName,ctx.getStart().getLine());
if (ctx.typedargslist()!=null) {
List<String> parameters = getParameterList(ctx.typedargslist().def_parameters());
for (String param : parameters) {
VarEntity paramEntity = context.addMethodParameter(param);
if (param.equals("self")) {
paramEntity.setType(context.currentType());
}
}
}
super.enterFuncdef(ctx);
}
@Override
public void exitFuncdef(FuncdefContext ctx) {
context.exitLastedEntity();
super.exitFuncdef(ctx);
}
@Override
public void enterClassdef(ClassdefContext ctx) {
String name = getName(ctx.name());
TypeEntity type = context.foundNewType(name, ctx.getStart().getLine());
List<String> baseClasses = getArgList(ctx.arglist());
baseClasses.forEach(base -> type.addExtends(GenericName.build(base)));
super.enterClassdef(ctx);
}
@Override
public void exitClassdef(ClassdefContext ctx) {
context.exitLastedEntity();
super.exitClassdef(ctx);
}
private List<String> getParameterList(List<Def_parametersContext> def_parameters) {
List<String> result = new ArrayList<>();
for (Def_parametersContext params:def_parameters) {
for (Def_parameterContext param:params.def_parameter()) {
if (!(param.named_parameter()==null)){
String p = getName( param.named_parameter().name());
result.add(p);
}
else{
// STAR, we ignore it
// refer to definition: def_parameter:named_parameter (ASSIGN test)? | STAR
}
}
}
return result;
}
private String getName(NameContext name) {
return name.getText();
}
private String getName(Dotted_nameContext dotted_name) {
return dotted_name.getText();
}
private String getDecoratedName(Class_or_func_def_stmtContext ctx) {
if (ctx.classdef()!=null) {
return getName(ctx.classdef().name());
}else if (ctx.funcdef()!=null) {
return getName(ctx.funcdef().name());
}
return null;
}
private List<String> getArgList(ArglistContext arglist) {
List<String> r = new ArrayList<>();
if (arglist==null) return r;
if (arglist.argument() == null) return r;
if (arglist.argument().isEmpty()) return r;
arglist.argument().forEach(arg->r.add(arg.getText()));
return r;
}
/**
* class_or_func_def_stmt: decorator+ (classdef | funcdef);
*/
@Override
public void exitClass_or_func_def_stmt(Class_or_func_def_stmtContext ctx) {
String decoratedName = getDecoratedName(ctx);
if (decoratedName!=null) {
Entity entity = context.foundEntityWithName(GenericName.build(decoratedName));
entity.setLine(ctx.getStart().getLine());
if (entity instanceof DecoratedEntity) {
for (DecoratorContext decorator: ctx.decorator()) {
String decoratorName = getName(decorator.dotted_name());
((DecoratedEntity) entity).addAnnotation(GenericName.build(decoratorName));
}
}
}
super.exitClass_or_func_def_stmt(ctx);
}
@Override
public void enterGlobal_stmt(Global_stmtContext ctx) {
for (NameContext name:ctx.name()){
VarEntity var = context.foundGlobalVarDefinition(context.currentFile(), name.getText(),ctx.getStart().getLine());
}
super.enterGlobal_stmt(ctx);
}
@Override
public void enterEveryRule(ParserRuleContext ctx) {
expressionUsage.foundExpression(ctx);
super.enterEveryRule(ctx);
}
@Override
public void enterExpr_stmt(Expr_stmtContext ctx) {
expressionUsage.startExpr();
super.enterExpr_stmt(ctx);
}
@Override
public void exitExpr_stmt(Expr_stmtContext ctx) {
expressionUsage.stopExpr();
super.exitExpr_stmt(ctx);
}
@Override
public void enterDel_stmt(Del_stmtContext ctx) {
expressionUsage.startExpr();
super.enterDel_stmt(ctx);
}
@Override
public void exitDel_stmt(Del_stmtContext ctx) {
expressionUsage.stopExpr();
super.exitDel_stmt(ctx);
}
@Override
public void enterReturn_stmt(Return_stmtContext ctx) {
expressionUsage.startExpr();
super.enterReturn_stmt(ctx);
}
@Override
public void exitReturn_stmt(Return_stmtContext ctx) {
expressionUsage.stopExpr();
super.exitReturn_stmt(ctx);
}
@Override
public void enterRaise_stmt(Raise_stmtContext ctx) {
expressionUsage.startExpr();
super.enterRaise_stmt(ctx);
}
@Override
public void exitRaise_stmt(Raise_stmtContext ctx) {
expressionUsage.stopExpr();
super.exitRaise_stmt(ctx);
}
@Override
public void enterYield_stmt(Yield_stmtContext ctx) {
expressionUsage.startExpr();
super.enterYield_stmt(ctx);
}
@Override
public void exitYield_stmt(Yield_stmtContext ctx) {
expressionUsage.stopExpr();
super.exitYield_stmt(ctx);
}
@Override
public void enterAssert_stmt(Assert_stmtContext ctx) {
expressionUsage.startExpr();
super.enterAssert_stmt(ctx);
}
@Override
public void exitAssert_stmt(Assert_stmtContext ctx) {
expressionUsage.stopExpr();
super.exitAssert_stmt(ctx);
}
}
| 14,225 | 32.472941 | 119 |
java
|
depends
|
depends-master/src/main/java/depends/extractor/python/union/ExpressionUsage.java
|
package depends.extractor.python.union;
import depends.entity.*;
import depends.entity.repo.IdGenerator;
import depends.extractor.HandlerContext;
import depends.extractor.python.PythonHandlerContext;
import depends.extractor.python.PythonParser.*;
import depends.extractor.python.PythonParserBaseListener;
import depends.extractor.python.PythonParserBaseVisitor;
import depends.relations.IBindingResolver;
import org.antlr.v4.runtime.ParserRuleContext;
import org.antlr.v4.runtime.RuleContext;
import org.antlr.v4.runtime.tree.ParseTreeWalker;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ExpressionUsage {
HandlerContext context;
IdGenerator idGenerator;
private boolean exprStarted=false;
private IBindingResolver bindingResolver;
public ExpressionUsage(PythonHandlerContext context, IdGenerator idGenerator, IBindingResolver bindingResolver) {
this.context = context;
this.idGenerator = idGenerator;
this.bindingResolver = bindingResolver;
}
/**
* Auto deduce variable type from assignment. for example: c = new C() then c is
* type of C
*
*/
private void deduceVarTypeInCaseOfAssignment(Expr_stmtContext expr, Expression expression) {
List<String> names = getName(expr.testlist_star_expr());
// TODO: should handle list properly;
String varName = null;
if (names.size() == 1)
varName = names.get(0);
if (varName == null)
return;
VarEntity var = context.lastContainer().lookupVarLocally(varName);
if (var != null) {
expression.addDeducedTypeVar(var);
}
}
private List<String> getName(Testlist_star_exprContext testlist_star_expr) {
List<String> names = new ArrayList<>();
testlist_star_expr.accept(new NameCollector(names));
return names;
}
private List<String> getName(List<Testlist_star_exprContext> testlist_star_expr) {
List<String> names = new ArrayList<>();
for (Testlist_star_exprContext expr:testlist_star_expr){
expr.accept(new NameCollector(names));
}
return names;
}
public void foundExpression(ParserRuleContext ctx) {
if (!isStartOfContainerRule(ctx)) {
return ;
}
if (context.lastContainer().containsExpression(ctx)) return;
if (ctx.getParent() instanceof TrailerContext) return;
Expression parent = findParentInStack(ctx);
Expression expression = parent;
if (ctx.getParent().getChildCount()==1 && parent!=null) {
//如果就是自己,则无需创建新的Expression
}else {
/* create expression and link it with parent*/
expression = new Expression(idGenerator.generateId());
expression.setLine(ctx.getStart().getLine());
expression.setText(ctx.getText());
context.lastContainer().addExpression(ctx,expression);
expression.setParent(parent);
}
if (ctx instanceof Expr_stmtContext) {
Expr_stmtContext exprAssign = (Expr_stmtContext)ctx;
if (exprAssign.assign_part()!=null) {
expression.setSet(true);
expression.setIdentifier(exprAssign.testlist_star_expr().getText());
if (isValidIdentifier(expression.getIdentifier())) {
if (!isAlias(exprAssign)){
makeSureVarExist(expression.getIdentifier(), ctx);
}
}
deduceVarTypeInCaseOfAssignment((Expr_stmtContext)ctx,expression);
}
}
if (ctx instanceof Raise_stmtContext) {
expression.setThrow (true);
}
if (ctx instanceof Return_stmtContext) {
deduceReturnTypeInCaseOfReturn((Return_stmtContext)ctx,expression);
}
if (ctx instanceof ExprContext) {
processExprContext((ExprContext)ctx, expression);
}
}
private boolean isAlias(Expr_stmtContext exprAssign) {
//if contain arguments, like a = A(), it must be a variable
if (containArguments(exprAssign)){
return false;
}
String theName = exprAssign.testlist_star_expr().getText();
List<String> assignNames = this.getName(exprAssign.assign_part().testlist_star_expr());
if (assignNames.size()==0) return false;
String assignName = namesToDot(assignNames);
Entity type = bindingResolver.resolveName(context.lastContainer(), GenericName.build(assignName),true);
if (type==null)
return false;
if (!(type instanceof TypeEntity))
return false;
context.foundNewAlias(theName,assignName);
return true;
}
private String namesToDot(List<String> assignNames) {
StringBuilder sb = new StringBuilder();
for (String s:assignNames){
if (sb.length()>0){
sb.append(".");
}
sb.append(s);
}
return sb.toString();
}
private boolean containArguments(Expr_stmtContext expr) {
final boolean[] containsArgument = {false};
PythonParserBaseListener visitor = new PythonParserBaseListener() {
@Override
public void enterArguments(ArgumentsContext ctx) {
containsArgument[0] = true;
super.enterArguments(ctx);
}
};
ParseTreeWalker walker = new ParseTreeWalker();
walker.walk(visitor,expr);
return containsArgument[0];
}
private void deduceReturnTypeInCaseOfReturn(Return_stmtContext ctx, Expression expression) {
FunctionEntity currentFunction = context.currentFunction();
if (currentFunction == null)
return;
expression.addDeducedTypeFunction(currentFunction);
}
private void makeSureVarExist(GenericName identifier, ParserRuleContext ctx) {
if (null==context.foundEntityWithName(identifier)) {
VarEntity var = context.foundVarDefinition(context.lastContainer(), identifier.getName(), ctx.getStart().getLine());
var.setLine(ctx.getStart().getLine());
}
}
private boolean isValidIdentifier(GenericName identifier) {
Pattern p = Pattern.compile("[a-zA-Z_][a-zA-Z0-9_]*");
Matcher m = p.matcher(identifier.getName());
return m.matches();
}
private void processExprContext(ExprContext exprCtx, Expression expression) {
//func_call, member_access, subscript member, and atom
Expression lastExpression = null;
if (exprCtx.atom()!=null) {
//atom
Expression atomExpr = new Expression(idGenerator.generateId());
atomExpr.setLine(exprCtx.atom().getStart().getLine());
atomExpr.setParent(expression);
atomExpr.setText(exprCtx.atom().getText());
atomExpr.setIdentifier(exprCtx.atom().getText());
context.lastContainer().addExpression(exprCtx.atom(),atomExpr);
processAtom(exprCtx.atom(),atomExpr);
lastExpression = atomExpr;
if (exprCtx.trailer()==null || exprCtx.trailer().size()==0) {
//do nothing; it is just an id;
}else {
for (TrailerContext trailer:exprCtx.trailer()) {
if (trailer.name()!=null) {
Expression trailerExpr = new Expression(idGenerator.generateId());
trailerExpr.setLine(trailer.getStart().getLine());
trailerExpr.setText(trailer.getText());
context.lastContainer().addExpression(trailer,trailerExpr);
trailerExpr.setParent(expression);
//doted name = member access or method call
trailerExpr.setDot(true);;
trailerExpr.setIdentifier(trailer.name().getText());
if (trailer.arguments()!=null) {
if (trailer.arguments().OPEN_PAREN()!=null) {
foundCallStyleExpressionWithDot(trailerExpr,lastExpression.getIdentifier(), trailer);
}else {
//subscript list, do nothing
}
}
lastExpression.setParent(trailerExpr);
lastExpression = trailerExpr;
}else {
//direct call, or direct data access
if (trailer.arguments()!=null) {
if (trailer.arguments().OPEN_PAREN()!=null) {
foundCallStyleExpressionWithoutDot(lastExpression, trailer.arguments());
}else {
//subscript list, do nothing
}
}
}
}
}
}else {
/** expr
| <assoc=right> expr op=POWER expr
| op=(ADD | MINUS | NOT_OP) expr
| expr op=(STAR | DIV | MOD | IDIV | AT) expr
| expr op=(ADD | MINUS) expr
| expr op=(LEFT_SHIFT | RIGHT_SHIFT) expr
| expr op=AND_OP expr
| expr op=XOR expr
| expr op=OR_OP expr
;*/
}
}
private boolean isStartOfContainerRule(ParserRuleContext ctx) {
if (this.exprStarted) return true;
return ctx instanceof ExprContext ||
ctx instanceof Expr_stmtContext ||
ctx instanceof Del_stmtContext ||
ctx instanceof Return_stmtContext ||
ctx instanceof Raise_stmtContext ||
ctx instanceof Raise_stmtContext ||
ctx instanceof Yield_stmtContext ||
ctx instanceof Assert_stmtContext;
}
private void foundCallStyleExpressionWithDot(Expression theExpression, GenericName varName, ParserRuleContext ctx) {
GenericName funcName = theExpression.getIdentifier();
Entity prefixEntity = context.foundEntityWithName(varName);
if (prefixEntity instanceof VarEntity) {
((VarEntity) prefixEntity).addFunctionCall(funcName);
}
Entity typeEntity = context.foundEntityWithName(funcName);
if (typeEntity instanceof TypeEntity && typeEntity.getId() > 0) {
theExpression.setCreate(true);
theExpression.setType(typeEntity.getType(), typeEntity, bindingResolver);
theExpression.setRawType(typeEntity.getRawName());
return;
}
theExpression.setCall(true);
}
private void foundCallStyleExpressionWithoutDot(Expression theExpression, ParserRuleContext ctx) {
GenericName funcName = theExpression.getIdentifier();
Entity typeEntity = context.foundEntityWithName(funcName);
if (typeEntity instanceof TypeEntity && typeEntity.getId() > 0) {
theExpression.getParent().setCreate(true);
theExpression.setType(typeEntity.getType(), typeEntity, bindingResolver);
theExpression.getParent().setRawType(typeEntity.getRawName());
return;
}
theExpression.setCall(true);
}
private void processAtom(AtomContext atom, Expression expression) {
if (atom.name()!=null) {
expression.setIdentifier(atom.getText());
return;
}
if (atom.STRING()!=null
|| atom.NONE()!=null
|| atom.number()!=null) {
expression.setRawType("<Built-in>");
expression.setIdentifier("<Literal>");
return;
}
if (atom.EXEC()!=null
|| atom.PRINT()!=null
|| atom.ELLIPSIS()!=null) {
return;
}
// : OPEN_PAREN (yield_expr | testlist_comp)? CLOSE_PAREN
// | OPEN_BRACKET testlist_comp? CLOSE_BRACKET
// | OPEN_BRACE dictorsetmaker? CLOSE_BRACE
// | REVERSE_QUOTE testlist COMMA? REVERSE_QUOTE
return;
}
private Expression findParentInStack(RuleContext ctx) {
if (ctx==null) return null;
if (ctx.parent==null) return null;
if (context.lastContainer()==null) {
return null;
}
if (context.lastContainer().expressions().containsKey(ctx.parent))
return context.lastContainer().expressions().get(ctx.parent);
return findParentInStack(ctx.parent);
}
public void startExpr() {
this.exprStarted = true;
}
public void stopExpr() {
this.exprStarted = false;
}
}
class NameCollector extends PythonParserBaseVisitor<Void>{
private List<String> names;
NameCollector(List<String> names){
this.names = names;
}
@Override
public Void visitName(NameContext ctx) {
names.add(ctx.getText());
return super.visitName(ctx);
}
}
| 10,890 | 29.940341 | 119 |
java
|
depends
|
depends-master/src/main/java/depends/extractor/python/union/PythonLexerBase.java
|
package depends.extractor.python.union;
import org.antlr.v4.runtime.CharStream;
import org.antlr.v4.runtime.CommonToken;
import org.antlr.v4.runtime.Lexer;
import org.antlr.v4.runtime.Token;
import depends.extractor.python.PythonLexer;
import java.util.Stack;
public abstract class PythonLexerBase extends Lexer {
public static int TabSize = 8;
// The amount of opened braces, brackets and parenthesis.
private int _opened;
// The stack that keeps track of the indentation level.
private Stack<Integer> _indents = new Stack<>();
// A circular buffer where extra tokens are pushed on (see the NEWLINE and WS lexer rules).
private int _firstTokensInd;
private int _lastTokenInd;
private Token[] _buffer = new Token[32];
private Token _lastToken;
protected PythonLexerBase(CharStream input) {
super(input);
}
@Override
public void emit(Token token) {
super.setToken(token);
if (_buffer[_firstTokensInd] != null)
{
_lastTokenInd = IncTokenInd(_lastTokenInd);
if (_lastTokenInd == _firstTokensInd)
{
// Enlarge buffer
Token[] newArray = new Token[_buffer.length * 2];
int destInd = newArray.length - (_buffer.length - _firstTokensInd);
System.arraycopy(_buffer, 0, newArray, 0, _firstTokensInd);
System.arraycopy(_buffer, _firstTokensInd, newArray, destInd, _buffer.length - _firstTokensInd);
_firstTokensInd = destInd;
_buffer = newArray;
}
}
_buffer[_lastTokenInd] = token;
_lastToken = token;
}
@Override
public Token nextToken() {
// Check if the end-of-file is ahead and there are still some DEDENTS expected.
if (_input.LA(1) == EOF && _indents.size() > 0)
{
if (_buffer[_lastTokenInd] == null || _buffer[_lastTokenInd].getType() != PythonLexer.LINE_BREAK)
{
// First emit an extra line break that serves as the end of the statement.
emit(PythonLexer.LINE_BREAK);
}
// Now emit as much DEDENT tokens as needed.
while (_indents.size() != 0)
{
emit(PythonLexer.DEDENT);
_indents.pop();
}
}
Token next = super.nextToken();
if (_buffer[_firstTokensInd] == null)
{
return next;
}
Token result = _buffer[_firstTokensInd];
_buffer[_firstTokensInd] = null;
if (_firstTokensInd != _lastTokenInd)
{
_firstTokensInd = IncTokenInd(_firstTokensInd);
}
return result;
}
protected void HandleNewLine() {
emit(PythonLexer.NEWLINE, HIDDEN, getText());
char next = (char) _input.LA(1);
// Process whitespaces in HandleSpaces
if (next != ' ' && next != '\t' && IsNotNewLineOrComment(next))
{
ProcessNewLine(0);
}
}
protected void HandleSpaces() {
char next = (char) _input.LA(1);
if ((_lastToken == null || _lastToken.getType() == PythonLexer.NEWLINE) && IsNotNewLineOrComment(next))
{
// Calculates the indentation of the provided spaces, taking the
// following rules into account:
//
// "Tabs are replaced (from left to right) by one to eight spaces
// such that the total number of characters up to and including
// the replacement is a multiple of eight [...]"
//
// -- https://docs.python.org/3.1/reference/lexical_analysis.html#indentation
int indent = 0;
String text = getText();
for (int i = 0; i < text.length(); i++) {
indent += text.charAt(i) == '\t' ? TabSize - indent % TabSize : 1;
}
ProcessNewLine(indent);
}
emit(PythonLexer.WS, HIDDEN, getText());
}
protected void IncIndentLevel() {
_opened++;
}
protected void DecIndentLevel() {
if (_opened > 0) {
--_opened;
}
}
private boolean IsNotNewLineOrComment(char next) {
return _opened == 0 && next != '\r' && next != '\n' && next != '\f' && next != '#';
}
private void ProcessNewLine(int indent) {
emit(PythonLexer.LINE_BREAK);
int previous = _indents.size() == 0 ? 0 : _indents.peek();
if (indent > previous)
{
_indents.push(indent);
emit(PythonLexer.INDENT);
}
else
{
// Possibly emit more than 1 DEDENT token.
while (_indents.size() != 0 && _indents.peek() > indent)
{
emit(PythonLexer.DEDENT);
_indents.pop();
}
}
}
private int IncTokenInd(int ind) {
return (ind + 1) % _buffer.length;
}
private void emit(int tokenType) {
emit(tokenType, DEFAULT_TOKEN_CHANNEL, "");
}
private void emit(int tokenType, int channel, String text) {
int charIndex = getCharIndex();
CommonToken token = new CommonToken(_tokenFactorySourcePair, tokenType, channel, charIndex - text.length(), charIndex);
token.setLine(getLine());
token.setCharPositionInLine(getCharPositionInLine());
token.setText(text);
emit(token);
}
}
| 5,486 | 28.342246 | 127 |
java
|
depends
|
depends-master/src/main/java/depends/extractor/python/union/PythonFileParser.java
|
package depends.extractor.python.union;
import depends.entity.repo.EntityRepo;
import depends.extractor.FileParser;
import depends.extractor.IncludedFileLocator;
import depends.extractor.python.PythonLexer;
import depends.extractor.python.PythonParser;
import depends.relations.IBindingResolver;
import multilang.depends.util.file.FileUtil;
import org.antlr.v4.runtime.CharStream;
import org.antlr.v4.runtime.CharStreams;
import org.antlr.v4.runtime.CommonTokenStream;
import org.antlr.v4.runtime.Lexer;
import org.antlr.v4.runtime.tree.ParseTreeWalker;
import java.io.IOException;
public class PythonFileParser extends FileParser {
private IBindingResolver bindingResolver;
private IncludedFileLocator includeFileLocator;
private PythonProcessor processor;
public PythonFileParser(EntityRepo entityRepo, IncludedFileLocator includeFileLocator,
IBindingResolver bindingResolver, PythonProcessor pythonProcessor) {
this.entityRepo = entityRepo;
this.bindingResolver = bindingResolver;
this.includeFileLocator = includeFileLocator;
this.processor = pythonProcessor;
}
@Override
protected void parseFile(String fileFullPath) throws IOException {
fileFullPath = FileUtil.uniqFilePath(fileFullPath);
CharStream input = CharStreams.fromFileName(fileFullPath);
Lexer lexer = new PythonLexer(input);
CommonTokenStream tokens = new CommonTokenStream(lexer);
PythonParser parser = new PythonParser(tokens);
PythonCodeListener bridge = new PythonCodeListener(fileFullPath, entityRepo, bindingResolver, includeFileLocator, processor);
ParseTreeWalker walker = new ParseTreeWalker();
walker.walk(bridge, parser.file_input());
}
}
| 1,716 | 36.326087 | 133 |
java
|
depends
|
depends-master/src/main/java/depends/extractor/python/union/PythonProcessor.java
|
package depends.extractor.python.union;
import depends.extractor.FileParser;
import depends.extractor.python.BasePythonProcessor;
import depends.extractor.IncludedFileLocator;
public class PythonProcessor extends BasePythonProcessor {
@Override
public boolean isEagerExpressionResolve(){
return true;
}
@Override
public String supportedLanguage() {
return "python";
}
@Override
public FileParser createFileParser() {
IncludedFileLocator includeFileLocator = new IncludedFileLocator(super.includePaths());
return new PythonFileParser(entityRepo,includeFileLocator, bindingResolver,this);
}
}
| 618 | 20.344828 | 89 |
java
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.