XNSim/XNSimHtml/utils/icd-parser.js

114 lines
3.4 KiB
JavaScript
Raw Permalink Normal View History

2025-05-07 13:46:48 +08:00
const XLSX = require('xlsx');
/**
* 解析数组维度字符串
* @param {string|number} dimensions - 数组维度字符串或数字 "10" "[10]" "[3][2]"
* @returns {Object} 包含数组维度的对象
*/
function parseArrayDimensions(dimensions) {
// 处理空值或1的情况
if (!dimensions || dimensions === '1' || dimensions === 1) {
return { isArray: false, arraySize1: 0, arraySize2: 0 };
}
// 确保dimensions是字符串
const dimStr = String(dimensions).trim();
// 尝试匹配形如 [10] 或 [3][2] 的格式
const bracketMatches = dimStr.match(/\[(\d+)\](?:\[(\d+)\])?/);
if (bracketMatches) {
const size1 = parseInt(bracketMatches[1]);
const size2 = bracketMatches[2] ? parseInt(bracketMatches[2]) : 0;
return {
isArray: true,
arraySize1: size1,
arraySize2: size2
};
}
// 尝试匹配纯数字格式
const numberMatch = dimStr.match(/^\d+$/);
if (numberMatch) {
const size = parseInt(numberMatch[0]);
return {
isArray: true,
arraySize1: size,
arraySize2: 0
};
}
// 如果都不匹配,则不是数组
return { isArray: false, arraySize1: 0, arraySize2: 0 };
}
/**
* 处理变量类型替换规则
* @param {string} type - 原始变量类型
* @returns {string} 替换后的变量类型
*/
function processVariableType(type) {
if (!type) return '';
const typeMap = {
'unsigned char': 'char',
'int': 'long'
};
return typeMap[type] || type;
}
2025-05-07 13:46:48 +08:00
/**
* 解析单个工作表
* @param {Object} worksheet - Excel工作表对象
* @param {string} structName - 结构体名称input/output
* @returns {Array} 解析后的数据数组
*/
function parseWorksheet(worksheet, structName) {
const data = XLSX.utils.sheet_to_json(worksheet);
return data.map(row => {
const dimensions = parseArrayDimensions(row['Variable Dimensions']);
return {
name: row['Input Variable Name'] || row['Output Variable Name'] || '',
description: row['Description'] || '',
structName: structName,
isArray: dimensions.isArray,
arraySize1: dimensions.arraySize1,
arraySize2: dimensions.arraySize2,
variableType: processVariableType(row['Variable Type'] || '')
2025-05-07 13:46:48 +08:00
};
});
}
/**
* 解析ICD Excel文件
* @param {string} filePath - Excel文件路径
* @returns {Promise<Array>} 解析后的数据数组
*/
async function parseICDFile(filePath) {
try {
const workbook = XLSX.readFile(filePath);
// 检查必要的工作表是否存在
if (!workbook.SheetNames.includes('Inputs') || !workbook.SheetNames.includes('Outputs')) {
throw new Error('ICD文件必须包含Inputs和Outputs两个工作表');
}
// 解析input工作表
const inputData = parseWorksheet(workbook.Sheets['Inputs'], 'input');
// 解析output工作表
const outputData = parseWorksheet(workbook.Sheets['Outputs'], 'output');
// 合并两个工作表的数据
return [...inputData, ...outputData];
} catch (error) {
console.error('解析ICD文件时出错:', error);
throw new Error('解析ICD文件失败: ' + error.message);
}
}
module.exports = {
parseICDFile
};