Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 | 925x 925x 925x 925x 930x 384x 38x 388x 116x 48x 68x 1x 67x 1x 66x 19x 19x 19x 2x 17x 14x 14x 14x 14x 14x 354x 354x 2x 352x 352x 352x 299x 53x 46x 7x 5x 2x 350x 350x 2x 348x 11x 135x 135x 132x 132x 11x 11x 11x 121x 121x 4x 117x 343x 343x 271x 72x 72x 72x 7x 65x 65x 1x 64x 64x 1x 63x 63x 1x 62x 62x 62x 291x 291x 290x 290x 128x 291x 98x 98x 62x 36x 66x 98x 45x 45x 45x 13x 32x 53x 53x 53x 53x 31x 22x 18x 4x 296x 296x 154x 154x 154x 154x 129x 25x 142x 142x 116x 26x 26x 26x 26x 1x 25x 14x 14x 12x 2x 2x 1x 1x 220x 65x 31x 21x 10x 4x 4x 6x 2x 2x 49x 49x 49x 9x 40x 49x 25x 49x 49x | /**
* TypeResolver - Handles type inference, classification, and validation
* Extracted from CodeGenerator for better separation of concerns
* Issue #61: Now independent of CodeGenerator
*/
import * as Parser from "../../logic/parser/grammar/CNextParser";
import ICodeGenSymbols from "../../types/ICodeGenSymbols";
import SymbolTable from "../../logic/symbols/SymbolTable";
import TTypeInfo from "./types/TTypeInfo";
import ITypeResolverDeps from "./types/ITypeResolverDeps";
import INTEGER_TYPES from "./types/INTEGER_TYPES";
import FLOAT_TYPES from "./types/FLOAT_TYPES";
import SIGNED_TYPES from "./types/SIGNED_TYPES";
import UNSIGNED_TYPES from "./types/UNSIGNED_TYPES";
import TYPE_WIDTH from "./types/TYPE_WIDTH";
import TYPE_RANGES from "./types/TYPE_RANGES";
import ExpressionUnwrapper from "./utils/ExpressionUnwrapper";
class TypeResolver {
private readonly symbols: ICodeGenSymbols | null;
private readonly symbolTable: SymbolTable | null;
private readonly typeRegistry: Map<string, TTypeInfo>;
private readonly resolveIdentifierFn: (name: string) => string;
constructor(deps: ITypeResolverDeps) {
this.symbols = deps.symbols;
this.symbolTable = deps.symbolTable;
this.typeRegistry = deps.typeRegistry;
this.resolveIdentifierFn = deps.resolveIdentifier;
}
/**
* ADR-024: Check if a type is any integer (signed or unsigned)
*/
isIntegerType(typeName: string): boolean {
return (INTEGER_TYPES as readonly string[]).includes(typeName);
}
/**
* ADR-024: Check if a type is a floating point type
*/
isFloatType(typeName: string): boolean {
return (FLOAT_TYPES as readonly string[]).includes(typeName);
}
/**
* ADR-024: Check if a type is a signed integer
*/
isSignedType(typeName: string): boolean {
return (SIGNED_TYPES as readonly string[]).includes(typeName);
}
/**
* ADR-024: Check if a type is an unsigned integer
*/
isUnsignedType(typeName: string): boolean {
return (UNSIGNED_TYPES as readonly string[]).includes(typeName);
}
/**
* Check if a type is a user-defined struct (C-Next or C header).
* Issue #103: Now checks both knownStructs AND SymbolTable.
* Issue #60: Uses SymbolCollector for C-Next structs.
* Issue #61: Uses injected dependencies instead of CodeGenerator.
*/
isStructType(typeName: string): boolean {
// Check C-Next structs first (Issue #60: use SymbolCollector)
if (this.symbols?.knownStructs.has(typeName)) {
return true;
}
// Issue #551: Bitmaps are struct-like (use pass-by-reference with -> access)
if (this.symbols?.knownBitmaps.has(typeName)) {
return true;
}
// Check SymbolTable for C header structs
if (this.symbolTable?.getStructFields(typeName)) {
return true;
}
return false;
}
/**
* ADR-024: Check if conversion from sourceType to targetType is narrowing
* Narrowing occurs when target type has fewer bits than source type
*/
isNarrowingConversion(sourceType: string, targetType: string): boolean {
const sourceWidth = TYPE_WIDTH[sourceType] || 0;
const targetWidth = TYPE_WIDTH[targetType] || 0;
if (sourceWidth === 0 || targetWidth === 0) {
return false; // Can't determine for unknown types
}
return targetWidth < sourceWidth;
}
/**
* ADR-024: Check if conversion involves a sign change
* Sign change occurs when converting between signed and unsigned types
*/
isSignConversion(sourceType: string, targetType: string): boolean {
const sourceIsSigned = this.isSignedType(sourceType);
const sourceIsUnsigned = this.isUnsignedType(sourceType);
const targetIsSigned = this.isSignedType(targetType);
const targetIsUnsigned = this.isUnsignedType(targetType);
return (
(sourceIsSigned && targetIsUnsigned) ||
(sourceIsUnsigned && targetIsSigned)
);
}
/**
* ADR-024: Validate that a literal value fits within the target type's range.
* Throws an error if the value doesn't fit.
* @param literalText The literal text (e.g., "256", "-1", "0xFF")
* @param targetType The target type (e.g., "u8", "i32")
*/
validateLiteralFitsType(literalText: string, targetType: string): void {
const range = TYPE_RANGES[targetType];
if (!range) {
return; // No validation for unknown types (floats, bools, etc.)
}
// Parse the literal value
let value: bigint;
try {
const cleanText = literalText.trim();
if (/^-?\d+$/.exec(cleanText)) {
// Decimal integer
value = BigInt(cleanText);
} else if (/^0[xX][0-9a-fA-F]+$/.exec(cleanText)) {
// Hex literal
value = BigInt(cleanText);
} else if (/^0[bB][01]+$/.exec(cleanText)) {
// Binary literal
value = BigInt(cleanText);
} else {
// Not an integer literal we can validate
return;
}
} catch {
return; // Can't parse, skip validation
}
const [min, max] = range;
// Check if value is negative for unsigned type
if (this.isUnsignedType(targetType) && value < 0n) {
throw new Error(
`Error: Negative value ${literalText} cannot be assigned to unsigned type ${targetType}`,
);
}
// Check if value is out of range
if (value < min || value > max) {
throw new Error(
`Error: Value ${literalText} exceeds ${targetType} range (${min} to ${max})`,
);
}
}
/**
* ADR-024: Get the type from a literal (suffixed or unsuffixed).
* Returns the explicit suffix type, or null for unsuffixed literals.
*/
getLiteralType(ctx: Parser.LiteralContext): string | null {
const text = ctx.getText();
// Boolean literals
if (text === "true" || text === "false") return "bool";
// Check for type suffix on numeric literals
const suffixMatch = /([uUiI])(8|16|32|64)$/.exec(text);
if (suffixMatch) {
const signChar = suffixMatch[1].toLowerCase();
const width = suffixMatch[2];
return (signChar === "u" ? "u" : "i") + width;
}
// Float suffix
const floatMatch = /[fF](32|64)$/.exec(text);
if (floatMatch) {
return "f" + floatMatch[1];
}
// Unsuffixed literal - type depends on context (handled by caller)
return null;
}
/**
* ADR-024: Get the type of an expression for type checking.
* Returns the inferred type or null if type cannot be determined.
* Issue #61: Uses ExpressionUnwrapper utility for tree navigation.
*/
getExpressionType(ctx: Parser.ExpressionContext): string | null {
// Navigate through expression tree to get the actual value
const postfix = ExpressionUnwrapper.getPostfixExpression(ctx);
if (postfix) {
return this.getPostfixExpressionType(postfix);
}
// For more complex expressions (binary ops, etc.), try to infer type
const ternary = ctx.ternaryExpression();
const orExprs = ternary.orExpression();
// If it's a ternary, we can't easily determine the type
if (orExprs.length > 1) {
return null;
}
const or = orExprs[0];
if (or.andExpression().length > 1) {
return "bool"; // Logical OR returns bool
}
const and = or.andExpression()[0];
if (and.equalityExpression().length > 1) {
return "bool"; // Logical AND returns bool
}
const eq = and.equalityExpression()[0];
if (eq.relationalExpression().length > 1) {
return "bool"; // Equality comparison returns bool
}
const rel = eq.relationalExpression()[0];
Iif (rel.bitwiseOrExpression().length > 1) {
return "bool"; // Relational comparison returns bool
}
// For arithmetic expressions, we'd need to track operand types
// For now, return null for complex expressions
return null;
}
/**
* ADR-024: Get the type of a postfix expression.
* Issue #304: Enhanced to track type through member access chains (e.g., cfg.mode)
* SonarCloud S3776: Refactored to use processSuffix helper.
*/
getPostfixExpressionType(
ctx: Parser.PostfixExpressionContext,
): string | null {
const primary = ctx.primaryExpression();
if (!primary) return null;
// Get base type from primary expression
let currentType = this.getPrimaryExpressionType(primary);
if (!currentType) return null;
// Check for postfix operations: member access, array indexing, bit indexing
const suffixes = ctx.children?.slice(1) || [];
for (const suffix of suffixes) {
const result = this.processPostfixSuffix(suffix.getText(), currentType);
if (result.stop) {
return result.type;
}
currentType = result.type!;
}
return currentType;
}
/**
* Process a single postfix suffix and determine the resulting type.
* Returns { type, stop } where stop=true means to return immediately.
*/
private processPostfixSuffix(
text: string,
currentType: string,
): { type: string | null; stop: boolean } {
// Member access: .fieldName
if (text.startsWith(".")) {
const memberName = text.slice(1);
const memberInfo = this.getMemberTypeInfo(currentType, memberName);
if (!memberInfo) {
return { type: null, stop: true };
}
return { type: memberInfo.baseType, stop: false };
}
// Array or bit indexing: [index] or [start, width]
Eif (text.startsWith("[") && text.endsWith("]")) {
return this.processIndexingSuffix(text, currentType);
}
// Unknown suffix, continue with current type
return { type: currentType, stop: false };
}
/**
* Process array or bit indexing suffix.
*/
private processIndexingSuffix(
text: string,
currentType: string,
): { type: string | null; stop: boolean } {
const inner = text.slice(1, -1);
// Range indexing: [start, width]
// ADR-024: Return null for bit indexing to skip type conversion validation
if (inner.includes(",")) {
return { type: null, stop: true };
}
// Single index: array access or bit indexing
// For single bit on integer, returns bool
if (this.isIntegerType(currentType)) {
return { type: "bool", stop: true };
}
// For arrays, currentType is already the element type
return { type: currentType, stop: false };
}
/**
* ADR-024: Get the type of a primary expression.
* Issue #61: Uses injected dependencies instead of CodeGenerator.
*/
getPrimaryExpressionType(
ctx: Parser.PrimaryExpressionContext,
): string | null {
// Check for identifier
const id = ctx.IDENTIFIER();
if (id) {
const name = id.getText();
const scopedName = this.resolveIdentifierFn(name);
const typeInfo = this.typeRegistry.get(scopedName);
if (typeInfo) {
return typeInfo.baseType;
}
return null;
}
// Check for literal
const literal = ctx.literal();
if (literal) {
return this.getLiteralType(literal);
}
// Check for parenthesized expression
const expr = ctx.expression();
Iif (expr) {
return this.getExpressionType(expr);
}
// Check for cast expression
const cast = ctx.castExpression();
if (cast) {
return cast.type().getText();
}
return null;
}
/**
* ADR-024: Get the type of a unary expression (for cast validation).
*/
getUnaryExpressionType(ctx: Parser.UnaryExpressionContext): string | null {
// Check for unary operators - type doesn't change for !, ~, -, +
const postfix = ctx.postfixExpression();
if (postfix) {
return this.getPostfixExpressionType(postfix);
}
// Check for recursive unary expression
const unary = ctx.unaryExpression();
if (unary) {
return this.getUnaryExpressionType(unary);
}
return null;
}
/**
* ADR-024: Validate that a type conversion is allowed.
* Throws error for narrowing or sign-changing conversions.
*/
validateTypeConversion(targetType: string, sourceType: string | null): void {
// If we can't determine source type, skip validation
if (!sourceType) return;
// Skip if types are the same
if (sourceType === targetType) return;
// Only validate integer-to-integer conversions
if (!this.isIntegerType(sourceType) || !this.isIntegerType(targetType))
return;
// Check for narrowing conversion
if (this.isNarrowingConversion(sourceType, targetType)) {
const targetWidth = TYPE_WIDTH[targetType] || 0;
throw new Error(
`Error: Cannot assign ${sourceType} to ${targetType} (narrowing). ` +
`Use bit indexing: value[0, ${targetWidth}]`,
);
}
// Check for sign conversion
if (this.isSignConversion(sourceType, targetType)) {
const targetWidth = TYPE_WIDTH[targetType] || 0;
throw new Error(
`Error: Cannot assign ${sourceType} to ${targetType} (sign change). ` +
`Use bit indexing: value[0, ${targetWidth}]`,
);
}
}
/**
* Get type info for a struct member field
* Used to track types through member access chains like buf.data[0]
* Issue #103: Now checks SymbolTable first for C header structs
* Issue #61: Uses injected dependencies instead of CodeGenerator.
*/
getMemberTypeInfo(
structType: string,
memberName: string,
): { isArray: boolean; baseType: string } | undefined {
// First check SymbolTable (C header structs) - Issue #103 fix
Eif (this.symbolTable) {
const fieldInfo = this.symbolTable.getStructFieldInfo(
structType,
memberName,
);
if (fieldInfo) {
return {
isArray:
fieldInfo.arrayDimensions !== undefined &&
fieldInfo.arrayDimensions.length > 0,
baseType: fieldInfo.type,
};
}
}
// Fall back to local C-Next struct fields (Issue #60: use SymbolCollector)
const fieldType = this.symbols?.structFields
.get(structType)
?.get(memberName);
if (!fieldType) return undefined;
// Check if this field is marked as an array (Issue #60: use SymbolCollector)
const arrayFields = this.symbols?.structFieldArrays.get(structType);
const isArray = arrayFields?.has(memberName) ?? false;
return { isArray, baseType: fieldType };
}
}
export default TypeResolver;
|