gpt4 book ai didi

c# - 查找在 Fortran 源文件中计算变量的位置

转载 作者:太空宇宙 更新时间:2023-11-03 10:54:17 25 4
gpt4 key购买 nike

我正在尝试用 C# 编写一个程序,以从数据库中获取一个字符串表(变量名称),并搜索包含约 30,000 个 Fortran 77 源文件的目录以确定该变量的计算位置。这些变量通常只在 1 个 fortran 文件中计算 1 次,但在其他文件中使用多次。数据库表中的变量都在 fortran 文件中的某处明确定义。到目前为止,我已经通过首先构建每个变量出现的文件列表,然后逐行搜索该列表中的文件来完成大部分工作。我一直在寻找变量出现在“=”符号的哪一侧,方法如下:

CompareInfo ci = CultureInfo.CurrentCulture.CompareInfo;
for (int k = 0; k < fullpaths.Count; k++)
{
string line;
// Read the file and display it line by line.
System.IO.StreamReader FortranFile = new System.IO.StreamReader(fullpaths[k]);
while ((line = FortranFile.ReadLine()) != null)
{
// Search the file line-by-line for the variable
if (ci.IndexOf(line, Variable, CompareOptions.IgnoreCase) > 0)
{
// Search for the equals sign
int equalLocation = ci.IndexOf(line, "=");
if (equalLocation > 0)
{
// substring LHS
string subLineLHS = line.Substring(0, equalLocation+1);
// is the line commented out?
if (Convert.ToString(subLineLHS[0]) == "C" ||
Convert.ToString(subLineLHS[0]) == "!" ||
Convert.ToString(subLineLHS[0]) == "c" ||
Convert.ToString(subLineLHS[0]) == "*")
{
continue;
}
// ignore if the line contains a DO, IF, or WHILE loop,
// to prevent reading IF [Variable] = xxxx as being calculated.
else if ( (ci.IndexOf(subLineLHS, "IF", CompareOptions.IgnoreCase) > 0) ||
(ci.IndexOf(subLineLHS, "DO", CompareOptions.IgnoreCase) > 0) ||
(ci.IndexOf(subLineLHS, "WHILE", CompareOptions.IgnoreCase) > 0))
{
continue;
}
// find where the variable is used in the line
else if (ci.IndexOf(subLineLHS, Variable, CompareOptions.IgnoreCase) > 0 )
{
isCalculated[k] = true;
calculatedLine[k] = counter;
}
}
} //if loop
counter++;
} //while loop

FortranFile.Close();
}

我遇到的问题是 IF 语句,例如:

   IF(something == xx .AND.
1 variable == xx) THEN
...

这个方法会告诉我变量是在“variable = xx”那一行计算的。 1 行 if 语句,如 IF(something) variable=xx 也被忽略。带有多个 = 符号的行也可能给我带来问题。

关于如何解决这个问题有什么建议吗?有更好的方法吗?请对我放轻松 - 我不是程序员。

谢谢!

最佳答案

最防错的方法是解析 Fortran 代码并从语法树开始工作。

我的建议:使用 ctags 。参见例如 Exuberant ctags ;它has support for Fortran . ctags生成一组源代码文件中所有命名实体的索引。索引存储在可以从大多数文件编辑器/IDE 中读取的数据结构(标签)中。如果您在您最喜欢的文本编辑器中导入该标签文件,当您将光标放在变量的定义上并采取适当的操作时,您将能够跳转到该变量的定义。

标签文件也很容易阅读和解析:它的结构是这样的。

named_entity<Tab>file_where_it_is_defined<Tab>location_in_the_file

例如,从一组 Fortran 文件(这是在 Linux 上,但 Exuberant ctags 提供 Windows binaries ):

gpar    remlf90.f90 /^           xrank,npar,gpar,/;"    v   program:REMLF90
hashia1 ../libs/sparse2.f /^ subroutine hashia1(/;" s
hashv1 ../libs/sparse3.f /^ integer function hashv1(/;" f
hashvr_old ../libs/sparse2.f /^ integer function hashvr_old(/;" f

我们可以观察到 gpar变量在 remlf90.f90 中定义和 hashia1../libs/sparse2.f 中定义等

关于c# - 查找在 Fortran 源文件中计算变量的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20080180/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com