Типов сообщений компилятора — более двухсот. Рассмотрим перечень наиболее встречающихся сообщений класса Error
- 0. <Что-то1> expected but <Что-то2> found. Обычно это сообщение возникает при синтаксической ошибке.Например,в случае небаланса скобок,компилятор сообщит: ‘)’ expected but ‘;’ found (вместо ожидавшейся скобки найдена запятая).
Компилятор часто сообщает, что ‘end’ ожидается,например:x:= 5,7; здесь неуместен разделитель-запятая, а сообщается про end. (‘END’ expected but ‘,’ found)
- 1. <Имя> is not a type identifier. Данное <Имя> не является именем типа.
- 2. ‘;’ not allowed before ‘Else’. Перед else нельзя ставить точку с запятой
- 3. Abstract method must be virtual or dynamic. Абстрактный метод должен быть виртуальным или динамическим.
- 4. Ambiguous overloaded call to <Имя блока>. Компилятор не может однозначно выбрать перегружаемый блок. Измените параметр.
- 5. Array type required. Ошибка возникает в случаях, когда в индексе элемента массива указано больше уровней, чем предусмотрено описанием, и если массив не описан. Например, после объявления двумерного массива х или простой переменной х ошибочно записывают элемент х[2,1,1] (в нем показано три измерения).
- 6. Assignment to FOR-loop variable <Имя>. Присваивание значения параметру FOR-цикла в теле цикла.
Например, вследствие описки дважды используется имя i в кратном цикле:
For i:= 1 to n do For i:= 1 to m do ...
- 7. Break or Continue outside of loop. Break или Continue — не в цикле.
- 8. Cannot initialize local variables. Локальные переменные запрещено инициализировать (задавать им значения при описании).
- 9. Cannot assign to/read a read-only/write-only property. Присвоение значения свойству read/only и чтение свойства write/only запрещены.
- 10. Constant expression expected.В этом месте должна стоять константа или константное выражение, например константа выбора в структуре Case.
- 11. Constant expression violates subrange bounds. Выход значения константы из диапазона. Контроль не полон. Например, «сойдет с рук» присваивание x:=3000000000, где х имеет тип integer, но начение х будет искажено.
- 12. Constant or type identifier expected. Требуется имя типа или тип-диапазон.
- 13. Could not compile used unit <Имя>. Компиляция присоединенного модуля <Имя> невозможна.
- 14. Data type too large. Тип определяет структуру размером более 2 Гбайт; это слишком много.
- 15. Declaration expected but <Что-то> found. Пропущено описание или оператор.
- 16. Declaration of <Имя> differs from previous declarations… Данный заголовок блока не соответствует упреждающему объявлению блока.
- 17. Default parameter <Имя> must be by-value or constant. Необязательный параметр (со значением по умолчанию) не должен вызываться по ссылке.
- 18. Expression expected. В этом месте программы должно стоять выражение.
- 19. Expression too complicated. Выражение излишне сложно для компиляции.
- 20. File type not allowed here. В этом месте или в этой роли файловую переменную нельзя использовать. Например, она не может быть формальным параметром-значением.
- 21. For loop control variable must be simple local variable. Параметр цикла должен быть простой локальной (описанной в этом же блоке) переменной.
- 22. For loop control variable must have ordinal type. Параметр цикла должен иметь порядковый тип.Вещественный тип запрещен.
- 23. Function needs result type. В заголовке функции надо указывать тип ее результата.
- 24. Identifier expected but <Что-то> found. В этом месте должно стоять имя. Например, пропущено имя функции после Function.
- 25. Identifier redeclared <Имя>.<Имя> описано повторно, но в пределах блока имя можно описать лишь раз. Проверьте, не обозначена ли локальная переменная тем же именем, что и формальный параметр блока.
- 26. Illegal character in input file <знак>. Запретный знак, например «русская» буква, либо вы оставили скобку }, убрав открывающую скобку {.
- 27. Illegal type in Read/Readln (Write/Writeln) statement. Элемент запрещенного типа в списке ввода/вывода.
- 28. Incompatible types <указание типов>. Несоответствие типов по присваиванию или типов операндов одной операции. Сообщение выдается и при неверном использовании структур. Например, z — запись, ошибочно записано присваивание z:= 0 (работать надо с полями записи).
- 29. Invalid function result type. Недопустимый тип результата функции.
- 30. Label already defined: <Метка>. <Метка> уже помечает другой оператор.
- 31. Left side cannot be assigned to. He может быть такой левой части в присваивании. Примеры: попытка присвоить значение файловой переменной, присвоение значения формальному параметру-константе.
- 32. Line too long. В строке программного текста больше 255 знаков.
- 33. Low bound exceeds high bound. Нижняя граница превышает верхнюю.
- 34. Missing operator or semicolon.Пропуск операции (например перед скобкой) или пропуск точки с запятой. При пропуске ‘;’ маркер ошибки стоит на очередном предложении (объявлении или операторе).
- 35. Missing parameter type. He указан тип формального параметра-значения или параметра процедурного типа.
- 36. Not enough actual parameters. He хватает фактических параметров.
- 37. Need to specify at least one dimension … Нужно задавать в операторе SetLength хотя бы один размер динамического массива.
- 38. Number of elements differs from declaration. Число элементов в структурной константе не соответствует ее описанию.
- 39. Operator not applicable to this operand type. Операция не применима к операндам данного типа. Например: ‘А’ or ‘В’; ‘Text1’* ‘Text2’.
- 40. Order of fields in record constant differs from declaration. Порядок полей в записи-константе не соответствует описанию записи.
- 41. Ordinal type required. Требуется порядковый тип (например, в индексе).
- 42. Out of memory. Компилятору не хватает памяти.
- 43. Statement expected but <Что-то> found. В этом месте должен стоять оператор. Сообщение выдается во всех случаях, когда в тело блока или секцию инициализации ошибочно помещают описание (<Что-то>). Ошибочная форма обращения к процедуре Procedure <Имя> или к функции Function <Имя> также вызывает сообщение.
- 44. Sets may have at most 256 elements. Множество (тип Set) не может содержать более 256 элементов.
- 45. Slice standard function only allowed as open array argument. Функцию Slice можно использовать лишь как фактический параметр
- 46. Statement not allowed in interface part. Предложения в секции интерфейса программного модуля недопустимы.
- 47. Syntax error in real number. Синтаксическая ошибка в записи числа вещственного типа.
- 48. There is no overload version of <Имя> that can be called with these arguments.Не предусмотрен перегружаемый блок <Имя>, который мог бы вызываться с таким аргументом. Пример: IntToStr(x), где х – выражение вещественного типа.
- 49. Too many actual parameters. Фактических параметров больше, чем формальных.
- 50. Type actual and formal var parameters must be identical. Тип фактического параметра должен быть идентичен типу формального параметра-переменной.
- 51. Type of expression must be <Тип>. Выражение должно быть указанного типа. Например,после While и Until должно стоять логическое выражение.
- 52. Undeclared identifier: <Имя>.Не описано <Имя>. Проверьте есть ли описание в нужном месте,нет ли описок в имени. Если указано имя компонента формы, проверьте,поместили ли компонент на данную форму.
- 53. Unexpected end of file in comment started on line <N>. Неожиданный конец файла при незавершенном комментарии, начало комментария — в строке N.
- 54. Unit name mismatch: <Имя>. Имя модуля ошибочно.
- 55. Unsatisfied forward or external declaration <Имя>. Отсутствует описание блока, объявление которого было дано (заголовок в интерфейсе или в описании объектного типа, либо упреждающее описание).
- 56. Unterminate string. He закрыта апострофом строка-константа типа string.
Рассмотрим также некоторые сообщения классов warning и hint.
- Return value of function <Имя> might be undefined. В теле функции нет присваивания ее результата.
- Variable <Имя> might not have been initialized. Указывает имя переменой, которой не задали значения.
- For-Loop variable <Имя> may be undefined after loop. Попытка использования значения параметра For-цикла после завершения этого цикла.
- Text after final ‘END.’ ignored by compiler. Текст, идущий за конечной строкой модуля, игнорируется компилятором.
- Variable <Имя> is declared but never used in <Имя блока>. Обращает внимание на переменную <Имя>, описанную,но не нашедшую применения.
- Value assigned to <Имя> never used. Хотя бы одно значение переменной <Имя> никак не использовано.
Несколько рекомендаций
Сосредотачивайтесь на первом сообщении компилятора. Исправление хотя бы одной ошибки и повторная компиляция может значительно уменьшить число сообщений об ошибках,поэтому не упорствуйте, стремясь понять сразу причину каждого сообщения.
Не удаляйте прежний вариант кода,пока не убедитесь,что ошибка устранена. Лучше на время закомментировать код,заключив его в скобки: { код }
Компилятор не анализирует, как будет выполняться программа, поэтому выход значения индекса из диапазона выявляет только если индекс задан константным выражением. Деление на ноль вообще пропускается, кроме оператора div, в случае если делитель — константное выражение.
I am toying around in Delphi XE6, and add this procedure on a button:
procedure TTabbedForm.btnLoadingClick(Sender: TObject);
var
dlg: Unit2;
begin
dlg := Form2.Create(nil);
Form2.ShowModal();
end;
Delphi gives me the following error while compiling:
[DCC Error] TabbedTemplate.pas(53): E2029 '.' expected but ';' found
[DCC Error] TabbedTemplate.pas(55): E2029 ';' expected but 'BEGIN' found
[DCC Fatal Error] Speelpleintjes.dpr(7): F2063 Could not compile used unit 'TabbedTemplate.pas'
Line 53 being: dlg: Unit2;
Honestly i’m quite puzzled, the syntax seems correct, the procedure is auto generated from the events tab.
Any suggestions?
Sir Rufo
18.2k2 gold badges39 silver badges72 bronze badges
asked Aug 24, 2014 at 20:56
3
If Unit2
is another unit in your project (judging by it’s name it probably is), it can’t be used as a type directly. Units only declare things. That’s why the compiler is expecting a .
since you can prefix an identifier with the unit’s name to direct to a declaration in that specific unit.
To correct this, write dlg: TForm2;
Also it’s common practice to call constructors from the class declaration, not a variable so change it to:
dlg := TForm2.Create(nil);
Or use the Form2
variable, which typically will hold an instance of TForm2
already. By default extra forms added to a Delphi project are created hidden, ready for Show
or ShowModal
.
answered Aug 25, 2014 at 6:41
Stijn SandersStijn Sanders
35.9k11 gold badges45 silver badges67 bronze badges
0
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 |
(...) procedure CodeAnalyze(LabelOffset: String; RepeatCycle: Boolean); procedure OneStringAnalyze(LabelOffset: String); var TE: PTreeElement; op: integer; begin op := GetCurrentWordIndex(index, Oper); if (op <> -1) then begin CodeAnalyze(LabelOffset, op = 4); Exit; end; Roll; end; procedure CodeAnalyze(LabelOffset: String; RepeatCycle: Boolean; First: Boolean); var op : Integer; TE : PTreeElement; LabelNumber: integer; GroupLabelNumber: integer; begin Roll; LabelNumber := 1; GroupLabelNumber := 1; op := GetCurrentWordIndex(index, Oper); if (op = -1) then begin TE := readExpression; if IsError then exit; EvaluateType(TE); if IsError then Exit; MakeCode(TE); if IsError then exit; Dispose(TE); Roll; if (Index = length(Code)) then begin Writeln('Unexpected end of file...' + IntToStr(GetStringNumber(Index))); IsError := True; Exit; end; end; while not ( ((Copy(Code, index, 3) = 'end') and (Code[Index+3] in delSet))) OR ( ((Copy(Code, index, 4) = 'else') and (Code[Index+4] in delSet))) do begin op := GetCurrentWordIndex(index, Oper); case op of 0: begin // if Index := Index + 2; Roll; TE := readExpression; if IsError then exit; EvaluateType(TE); if IsError then Exit; if (TE.Type_.Type_ <> Boolean_) then begin Writeln('Extension is''not boolean type...' + IntToStr(GetStringNumber(Index))); IsError := True; Exit; end; MakeCode(TE); if IsError then exit; Dispose(TE); Roll; if not ((Copy(Code, index, 4) = 'then') and (Code[Index+4] in [' '])) then begin Writeln('"then" expected...' + IntToStr(GetStringNumber(Index))); IsError := True; Exit; end; Inc(Index, 4); Roll; ResultList.Add('PopInt #Temp1'); ResultList.Add('LDA Temp1'); ResultList.Add('LDB 1'); ResultList.Add('COMPR A, B'); ResultList.Add('JNE '+LabelOffset + '_'+IntToStr(LabelNumber)); OneStringAnalyze(LabelOffset+'_'+IntToStr(GroupLabelNumber)); if IsError then Exit; Inc(GroupLabelNumber); Roll; if Code[Index] = ';' then begin ResultList.Add(LabelOffset+'_'+IntToStr(LabelNumber)); end else begin if ((Copy(Code, index, 4) = 'else') and (Code[Index+4] in [' '])) then begin index := index + 4; Roll; ResultList.Add('J '+LabelOffset+'_'+IntToStr(LabelNumber+1)); ResultList.Add(LabelOffset+'_'+IntToStr(LabelNumber)); OneStringAnalyze(LabelOffset+'_'+IntToStr(GroupLabelNumber)); if IsError then exit; Inc(LabelNumber); Inc(GroupLabelNumber); ResultList.Add(LabelOffset+'_'+IntToStr(LabelNumber)); Roll; end else begin Writeln('"else" expected...' + IntToStr(GetStringNumber(Index))); IsError := True; Exit; end; end; Roll; if Code[index]<> ';' then begin Writeln('";" expected...' + IntToStr(GetStringNumber(Index))); IsError := True; Exit; end; Inc(Index); Inc(LabelNumber); Roll; end; 1:begin // case Index := Index + 4; Roll; TE := readExpression; if IsError then exit; EvaluateType(TE); if IsError then Exit; end; // 2: 3:begin //while Index := Index + 5; Roll; ResultList.Add(LabelOffset+'_'+IntToStr(LabelNumber)); TE := readExpression; if IsError then exit; EvaluateType(TE); if IsError then Exit; if (TE.Type_.Type_ <> Boolean_) then begin Writeln('Extension is''not boolean type...' + IntToStr(GetStringNumber(Index))); IsError := True; Exit; end; MakeCode(TE); if IsError then exit; Dispose(TE); Roll; if not ((Copy(Code, index, 2) = 'do') and (Code[Index+2] in [' '])) then begin Writeln('"do" expected...' + IntToStr(GetStringNumber(Index))); IsError := True; Exit; end; Inc(Index, 2); Roll; ResultList.Add('PopInt #Temp1'); ResultList.Add('LDA Temp1'); ResultList.Add('LDB 1'); ResultList.Add('COMPR A, B'); ResultList.Add('JNE '+LabelOffset + '_'+IntToStr(LabelNumber+1)); if not ((Copy(Code, index, 5) = 'begin') and (Code[Index+5] in [' ', ';', ',', '=', '+', '-', '(', ')', '[', ']', '/', '*','^', '.',':'])) then begin OneStringAnalyze(LabelOffset + '_'+IntToStr(GroupLabelNumber)); Inc(GroupLabelNumber); end else begin Inc(Index, 5); Roll; CodeAnalyze(LabelOffset + '_'+IntToStr(GroupLabelNumber), false, false); Inc(GroupLabelNumber); end; if IsError then exit; Roll; ResultList.Add('J '+LabelOffset+'_'+IntToStr(LabelNumber)); ResultList.Add(LabelOffset+'_'+IntToStr(LabelNumber+1)); if IsError then exit; Roll; if Code[index]<> ';' then begin Writeln('";" expected...' + IntToStr(GetStringNumber(Index))); IsError := True; Exit; end; Inc(Index); Inc(LabelNumber,2); Roll; end; // 4: // 5: // 6: else begin TE := readExpression; if IsError then exit; EvaluateType(TE); if (TE.Type_.Type_ <> NoType_) then begin Writeln('Statement mustn''t have result type...' + IntToStr(GetStringNumber(Index))); IsError := True; Exit; end; if IsError then Exit; MakeCode(TE); if IsError then exit; Dispose(TE); Roll; if (Index = length(Code)) then begin Writeln('Unexpected end of file...' + IntToStr(GetStringNumber(Index))); IsError := True; Exit; end; if (Code[Index] <> ';') then begin if (not ((Copy(Code, index, 3) = 'end') and (Code[Index+3] in [' ', ';', '.']))) AND (not ((Copy(Code, index, 4) = 'else') and (Code[Index+4] in delSet))) then begin Writeln('";" expected...' + IntToStr(GetStringNumber(Index))); IsError := True; Exit; end; end; if Code[Index] = ';' then Inc(Index); Roll; end; end; end; if (not RepeatCycle) and not((Code[Index+3] in [' ', ';','.'])) then begin Writeln('";", " ", "." expected...' + IntToStr(GetStringNumber(Index))); IsError := True; Exit; end; if not RepeatCycle then Index := index + 3; end; //Основная функция разбора выражений. procedure Parse; begin Index := 1; ConstsCount := 0; TypesCount := 0; VarsCount := 0; GetProgramName; ResultList.Add('J Start'); ResultList.Add('IntStack BYTE ' + GetZeros(50)); ResultList.Add('FloatStack BYTE ' + GetZeros(50)); ResultList.Add('IntP WORD 0'); ResultList.Add('RealP WORD 0'); ResultList.Add('Temp1 WORD 0'); ResultList.Add('Temp2 WORD 0'); InData := True; if IsError then Exit; Roll; while InData do begin case GetCurrentWordIndex(Index, Del) of -1: begin // command is absent Writeln('Special command is waited...' + IntToStr(GetStringNumber(Index))); IsError := True; Exit; end; 0: ConstAnalyze; // const fields analyze 1: VarAnalyze; // variable fields analyze 2: TypeAnalyze; // type fields analyze //3: // procedure analyze //4: // function analyze 5: begin InData := False; Index := Index+5; CodeAnalyze('L', False, false); Roll; if Code[Index] <> '.' then begin Writeln('"." expected...' + IntToStr(GetStringNumber(Index))); IsError := True; Exit; end; ResultList.Add('RSUB'); Break; // start of program end; end; if IsError then Exit; end; end; var i : Integer; str: string; BEGIN if ParamCount <> 2 then begin Writeln('Invalid count of parameters'); Exit; end; IsError := False; Writeln('In file: ' + ParamStr(1)); Writeln('Out file: ' + ParamStr(2)); SL := TStringList.Create; ResultList := TStringList.Create; SL.LoadFromFile(ParamStr(1)); ConvertStrings; ConvertCodeToString; Parse; SL.Free; ResultList.SaveToFile(ParamStr(2)); ResultList.Free; Readln; END. |
Go Up to Error and Warning Messages (Delphi)
This error message appears for syntax errors. There is probably a typo in the source, or something was left out. When the error occurs at the beginning of a line, the actual error is often on the previous line.
program Produce; var I: Integer begin (*<-- Error message here: ';' expected but 'BEGIN' found*) end.
After the type Integer, the compiler expects to find a semicolon to terminate the variable declaration. It does not find the semicolon on the current line, so it reads on and finds the ‘begin’ keyword at the start of the next line. At this point it finally knows something is wrong…
program Solve; var I: Integer; (*Semicolon was missing*) begin end.
In this case, just the semicolon was missing — a frequent case in practice. In general, have a close look at the line where the error message appears, and the line above it to find out whether something is missing or misspelled.
20-05-2012 |
|||
|
|||
Pues hize un programa en delphi y a la hora de depurarlo me da este error:
|
20-05-2012 |
||||
|
||||
El error, en principio, est� claro:
|
20-05-2012 |
||||
|
||||
Bueno, por lo que veo est�s utilizando el programa «DeDe» que es un De-compilador de programas en Delphi… asi que no deber�as decir: «hice un programa en Delphi» Teniendo en cuenta esto, me adhiero al comentario de Casimiro, el error es claro y transparente… pues el tipo N.A. no existe..
|
20-05-2012 |
||||
|
||||
Me adhiero, encima de usar un decompilador ni siquiera tiene idea de lo que le presenta, ya no digamos de la sintaxis correcta de Delphi. Ya muchos de los que s� programamos nos dimos cuenta del error generado. Y en efecto como dice gatosoft no esperes que todo se revele como magia y sobre todo sin tener la menor idea de en que te est�s metiendo. |
20-05-2012 |
|||
|
|||
Error Delphi Depuracion Pues con DeDe el descompilador, descompile un programa para editarlo ya esta listo o eso creo y me da este error:
|
20-05-2012 |
||||
|
||||
Hola H8RS. Comb�n� tu �ltimo mensaje (que iniciaste como nuevo hilo) ya que es continuaci�n de este. Cuando un mensaje tenga conexi�n con un hilo que ya iniciaste por favor agregalo a ese hilo, no crees uno nuevo. De otro modo qui�n lo lee, no tiene idea de lo expuesto anteriormente. Saludos. |