Debian Codegraph @

src/scene/castleinternalx3dlexer.pas

raw
1 {
2 Copyright 2002-2018 Michalis Kamburelis.
3
4 This file is part of "Castle Game Engine".
5
6 "Castle Game Engine" is free software; see the file COPYING.txt,
7 included in this distribution, for details about the copyright.
8
9 "Castle Game Engine" is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
12
13 ----------------------------------------------------------------------------
14 }
15
16 { VRML/X3D classic lexer (TX3DLexer). }
17 unit CastleInternalX3DLexer;
18
19 {$I castleconf.inc}
20
21 interface
22
23 uses SysUtils, Classes, CastleUtils, CastleStringUtils, CastleClassUtils,
24 Math;
25
26 type
27 { Valid keywords for all VRML / X3D versions. }
28 TX3DKeyword = (vkDEF, vkEXTERNPROTO, vkFALSE, vkIS, vkNULL, vkPROTO, vkROUTE,
29 vkTO, vkTRUE, vkUSE, vkEventIn, vkEventOut, vkExposedField, vkField,
30 { Below keywords are X3D-only as far as specification is concerned.
31 However, we decide to support IMPORT/EXPORT for older VRML versions
32 too (the downside is that you cannot name your nodes like this,
33 but the upside is that you can use these features in all VRML versions.) } { }
34 vkAS, vkEXPORT, vkIMPORT,
35 { X3D-only keywords below } { }
36 vkCOMPONENT, vkMETA, vkPROFILE, vkUNIT,
37 vkInputOnly, vkOutputOnly, vkInputOutput, vkInitializeOnly);
38
39 TX3DKeywords = set of TX3DKeyword;
40
41 const
42 VRML10Keywords = [vkDEF, vkUSE, vkFALSE, vkTRUE];
43 VRML20Keywords = [vkDEF .. vkIMPORT] +
44 { META accepted as Titania demos use it } [vkMETA];
45 X3DKeywords = [Low(TX3DKeyword) .. High(TX3DKeyword)] -
46 [vkEventIn, vkEventOut, vkExposedField, vkField];
47
48 type
49 { Lexer token. }
50 TX3DToken = (
51 vtKeyword,
52 vtName,
53
54 { Symbols for all VRML versions.
55 @groupBegin }
56 vtOpenCurlyBracket, vtCloseCurlyBracket,
57 vtOpenSqBracket, vtCloseSqBracket,
58 { @groupEnd }
59
60 { Symbols below are only for VRML <= 1.0.
61 In VRML 2.0, they are no longer valid symbols
62 (comma is even considered a whitespace).
63 They will never be returned by lexer when reading VRML >= 2.0 files.
64
65 @groupBegin }
66 vtOpenBracket, vtCloseBracket, vtBar, vtComma,
67 { @groupEnd }
68
69 { Symbols below are only for VRML >= 2.0.
70 They will never be returned by lexer when reading VRML < 2.0 files.
71 @groupBegin }
72 vtPeriod,
73 { @groupEnd }
74
75 { Symbols below are only for VRML >= 3.0, that is X3D.
76 They will never be returned by lexer when reading VRML < 3.0 files.
77 @groupBegin }
78 vtColon,
79 { @groupEnd }
80
81 { Back to version-neutral tokens, suitable for all VRML / X3D versions.
82 @groupBegin }
83 vtFloat, vtInteger, vtString,
84 { @groupEnd }
85
86 { vtEnd means that we're standing at the end of stream, no more tokens.
87 From this point, further reads using NextToken from stream will
88 always result in vtEnd (they will not raise an error). }
89 vtEnd);
90 TX3DTokens = set of TX3DToken;
91
92 { Any error related to VRML/X3D. }
93 EX3DError = class(Exception);
94
95 EGzipCompressed = class(Exception);
96
97 const
98 TokenNumbers : TX3DTokens = [vtFloat, vtInteger];
99
100 type
101 TX3DEncoding = (xeClassic, xeXML);
102
103 TX3DVersion = record
104 Major, Minor: Integer;
105 end;
106
107 { VRML/X3D (classic encoding) lexer.
108
109 The lexer always "looks" (i.e. contains in Token and TokenXxx fields)
110 at the next not yet interpreted token.
111
112 Remember that VRML is case-sensitive, so TokenName and TokenString
113 should be compared in case-sensitive manner. Also note that
114 for VRML/X3D >= 2.0 these fields contain UTF-8 encoded strings.
115
116 Note that this lexer can read only from @link(TPeekCharStream), not just
117 from any TStream. You may have to wrap your stream in some
118 @link(TPeekCharStream) descendant (for example create TFileStream
119 and then wrap it inside @link(TBufferedReadStream)). }
120 TX3DLexer = class
121 private
122 fVersion: TX3DVersion;
123 fToken: TX3DToken;
124 fTokenKeyword: TX3DKeyword;
125 fTokenName: string;
126 fTokenFloat: Float;
127 fTokenInteger: Int64;
128 fTokenString: string;
129
130 VRMLWhitespaces, VRMLNoWhitespaces: TSetOfChars;
131 VRMLNameChars, VRMLNameFirstChars: TSetOfChars;
132
133 FStream: TPeekCharStream;
134 FOwnsStream: boolean;
135
136 { Reads chars from Stream until EOF or some non-white char will
137 be approached. Omits VRML comments. Returns as FirstBlack
138 -1 (if EOF) or Ord(of this non-white char). (This non-white
139 char will be already read from Stream, so usually you MUST do
140 something with returned here FirstBlack, you can't ignore him) }
141 procedure StreamReadUptoFirstBlack(out FirstBlack: Integer);
142
143 { Read string. Initial " has been already read. Reads everything
144 up to (and including) " terminating the string.
145 Sets fToken and fTokenString to appropriate values
146 (i.e. fToken always to vtString, fTokenString to string contents). }
147 procedure ReadString;
148
149 { Helpers for implementing constructors. They do everything, besides
150 reading header from the stream (before the first real token)
151 and setting VRMLVerXxx fields, you must do it between the call
152 to CreateCommonBegin and CreateCommonEnd.
153
154 @groupBegin }
155 procedure CreateCommonBegin(AStream: TPeekCharStream;
156 AOwnsStream: boolean);
157 procedure CreateCommonEnd;
158 { @groupEnd }
159 public
160 { Standard constructor.
161 After constructor call, @link(Version) is already set,
162 it's checked that file is not compressed by gzip, and the first
163 Token is already read.
164 @raises(EGzipCompressed If the Stream starts with gzip file header.) }
165 constructor Create(AStream: TPeekCharStream; AOwnsStream: boolean);
166
167 { Constructor for the case when you only have part of normal
168 VRML tokens stream.
169
170 This is particularly useful to parse fields of X3D in XML encoding.
171 Inside XML attributes we have then a text that can parsed with
172 a classical VRML lexer, to parse fields contents.
173
174 This creates a lexer that works quite like a normal lexer.
175 At creation time it doesn't expect header line (like @code(#VRML 2.0 utf8)),
176 that why you have to supply VRML major and minor version as
177 parameters here. Also it doesn't try to detect gzip header.
178 It simply behaves like we're in the middle of VRML tokens stream.
179
180 Overloaded version with a first parameter as string simply reads
181 tokens from this string (wrapping it in TStringStream and TPeekCharStream).
182
183 @groupBegin }
184 constructor CreateForPartialStream(
185 AStream: TPeekCharStream; AOwnsStream: boolean;
186 const AVersion: TX3DVersion); overload;
187 constructor CreateForPartialStream(const S: string;
188 const AVersion: TX3DVersion); overload;
189 { @groupEnd }
190
191 destructor Destroy; override;
192
193 { The stream we're reading.
194 This is simply the AStream that you passed to the constructor
195 of this class.
196
197 Note that you can't operate on this stream from outside while lexer
198 works, this could confuse the lexer. But you're free to read
199 some stream properties, e.g. check Stream.Position. }
200 property Stream: TPeekCharStream read FStream;
201
202 { VRML/X3D version, as recorded in the file header.
203
204 All VRML 1.0, 2.0, X3D (various 3.x) are recognized correctly.
205 For Inventor 1.0 ascii, we set Version.Major to 0
206 (as historically Inventor is a predecessor to VRML 1.0). }
207 property Version: TX3DVersion read fVersion;
208
209 { Token we're currently standing on.
210 TokenKeyword, TokenName, TokenFloat and TokenInteger have defined
211 values only when token type is appropriate. }
212 property Token: TX3DToken read fToken;
213
214 { When Token = vtKeyword, TokenKeyword points to appropriate keyword.
215
216 When Version.Major = 1, then you can be sure that TokenKeyword is
217 in VRML10Keywords. Analogous for VRML20Keywords and X3DKeywords.
218 So e.g. in VRML 1.0 "PROTO" will be treated like a normal name,
219 not a start of prototype. }
220 property TokenKeyword: TX3DKeyword read fTokenKeyword;
221
222 { When Token = vtName, TokenName contains appropriate VRML name.
223
224 Name syntax as in specification on page 24 (really 32 in pdf) of
225 vrml97specification.pdf. It can be a user name for something (for a node,
226 for example) but it can also be a name of a node type or a node field
227 or an enumerated field constant ... it can be @italic(anything)
228 except keyword.
229
230 Note that this is supposed to contain UTF-8 encoded string for VRML >= 2.0. }
231 property TokenName: string read fTokenName;
232
233 { TokenName, decoded using DecodeX3DName. }
234 function TokenX3DName: String;
235
236 { When Token = vtFloat or vtInteger, TokenFloat contains a value of
237 this token.
238
239 For vtInteger you have the same thing in TokenInteger,
240 TokenFloat is also initialized to the same value for your comfort
241 (every integer value is also a float, after all). }
242 property TokenFloat: Float read fTokenFloat;
243
244 { When Token = vtInteger, TokenInteger contains appropriate value. }
245 property TokenInteger: Int64 read fTokenInteger;
246
247 { When Token = vtString, TokenString contains string value. }
248 property TokenString: string read fTokenString;
249
250 { NextToken reads next token from stream, initializing appropriately
251 all Token* properties. For comfort, this returs the new value of
252 @link(Token) property. }
253 function NextToken: TX3DToken;
254
255 { Read the next token, knowing that it @italic(must) be vtName token.
256 This is basically a dirty hack to read some incorrect VRML files,
257 that use not allowed characters in VRML names. This allows us to
258 accept as a vtName some characters that normally (when using normal
259 NextToken) would get interpreted as other token.
260
261 For example, mgf2inv can write name @code(0) (a zero, that would be
262 read as vtInteger token in normal circumstances), on some WWW page
263 I found sample VRML models with node name @code("Crab!") (yes,
264 with exclamation mark and double quotes as part of the node name).
265
266 @raises(EX3DParserError When we really really cannot interpret contents
267 as vtName token here --- currently this may happen only if end of
268 stream is reached. Note that this is reported as a parsing error.) }
269 procedure NextTokenForceVTName;
270
271 { Read the next token, knowing that it @italic(must) be vtString token.
272
273 Similiar to NextTokenForceVTName: use this like a shortcut for
274
275 @longCode(#
276 NextToken;
277 CheckTokenIs(vtString);
278 #)
279
280 but it is not equivalent to such instructions. This is because
281 VRML 1.0 allowed rather strange thing: string may be not enclosed
282 in double quotes if it does not contain a space. This "feature"
283 is not present in VRML >= 2.0, but, unfortunately, I'm trying to handle
284 VRML 1.0 here so I have to conform to this specification.
285 In particular, Blender generates VRML 1.0 files with Texture2.filename
286 fields not enclosed in double quotes. So this "feature" is actually
287 used by someone... So I have to implement this.
288
289 Usual NextToken will not be able to return vtString if it approaches
290 a string not enclosed in double quotes. But THIS function
291 will be able to handle it. So always use this function when
292 you expect a string, this ensures
293 that we will correctly parse any valid VRML 1.0 file.
294
295 (unfortunately I'm not doing this now when parsing MFString,
296 this would just require too "unclean" code; I'm using this
297 function only before calling parse on SFString field from
298 TX3DNode.Parse.) }
299 procedure NextTokenForceVTString;
300
301 { Returns if Token is vtKeyword and TokenKeyword is given Keyword. }
302 function TokenIsKeyword(const Keyword: TX3DKeyword): boolean; overload;
303 function TokenIsKeyword(const Keywords: TX3DKeywords): boolean; overload;
304
305 { Nice textual description of current token, suitable to show to user. }
306 function DescribeToken: string;
307
308 { Check is token = Tok, if not -> parser error "expected token 'tok'".
309 You can provide your own description for Tok or default desciption
310 for token will be used. }
311 procedure CheckTokenIs(Tok: TX3DToken); overload;
312 procedure CheckTokenIs(Tok: TX3DToken; const TokDescription: string); overload;
313 procedure CheckTokenIs(const Toks: TX3DTokens; const ToksDescription: string); overload;
314 procedure CheckTokenIsKeyword(const Keyword: TX3DKeyword);
315 end;
316
317 { Error when reading VRML/X3D classic encoding. }
318 EX3DClassicReadError = class(EX3DError)
319 public
320 { Standard constructor.
321
322 Lexer instance must be valid for this call, but not longer.
323 That is, you can free the lexer after this constructor finished,
324 it doesn't need to be valid for the whole lifetime of this object. }
325 constructor Create(Lexer: TX3DLexer; const s: string);
326 end;
327
328 { Error when reading VRML/X3D. For now, just equal to EX3DClassicReadError,
329 later may be an ancestor to EX3DClassicReadError.
330 Problems in other encodings (XML) are for now always turned into warnings. }
331 EX3DReadError = EX3DClassicReadError;
332
333 EX3DLexerError = class(EX3DClassicReadError);
334 EX3DParserError = class(EX3DClassicReadError);
335
336 const
337 X3DKeywordsName: array [TX3DKeyword] of string = (
338 'DEF', 'EXTERNPROTO', 'FALSE', 'IS', 'NULL', 'PROTO', 'ROUTE',
339 'TO', 'TRUE', 'USE', 'eventIn', 'eventOut', 'exposedField', 'field',
340 'AS', 'EXPORT', 'IMPORT',
341 'COMPONENT', 'META', 'PROFILE', 'UNIT',
342 'inputOnly', 'outputOnly', 'inputOutput', 'initializeOnly'
343 );
344
345 { String encoded for VRML/X3D classic, surrounded by double quotes.
346 You can use this when generating VRML/X3D content by hand.
347
348 Simply put, this just adds
349 double quotes around and prepends backslash to all " and \ inside.
350 Fortunately, no other characters (including newlines) need to be quoted
351 in any special way for VRML/X3D.
352 For example:
353
354 @longCode(#
355 StringToX3DClassic('foo') = '"foo"'
356 StringToX3DClassic('say "yes"') = '"say \"yes\""'
357 #) }
358 function StringToX3DClassic(const s: string;
359 const SurroundWithQuotes: boolean = true): string;
360
361 { String encoded for X3D XML, surrounded by double quotes.
362 You can use this when generating VRML/X3D content by hand.
363
364 Simply put, this just adds double quotes around and replaces
365 all special characters (quotes, double quotes and more)
366 with appropriate XML entities &xxx;. }
367 function StringToX3DXml(const s: string): string;
368
369 { String encoded for X3D XML, surrounded by double quotes, to be used
370 as part of MFString.
371
372 In addition to what StringToX3DXml does, this additionally
373 adds backslash before &quot; (double quotes), and doubles existing backslashes.
374 Otherwise XML reader
375 may not tell the difference between double quotes delimiting single string
376 item and double quotes inside, as it has to (and DOM units do) treat
377 " and &quot; exactly the same. X3D XML encoding spec shows example
378 confirming this is correct,
379 @code(<Text string='"He said, \&quot;Immel did it!\&quot;"' />). }
380 function StringToX3DXmlMulti(const s: string): string;
381
382 implementation
383
384 uses CastleLog,
385 X3DLoadInternalUtils;
386
387 const
388 { utf8 specific constants below }
389 X3DLineTerm = [#10, #13];
390
391 X3DTokenNames: array [TX3DToken] of string = (
392 'keyword', 'name',
393 '"{"', '"}"', '"["', '"]"', '"("', '")"', '"|"', '","', '"."', '":"',
394 'float', 'integer', 'string', 'end of stream');
395
396 var
397 { Log all read tokens. Useful for debugging lexer. }
398 LogTokens: boolean = false;
399
400 function ArrayPosX3DKeywords(const s: string; out Index: TX3DKeyword): boolean;
401 var
402 I: TX3DKeyword;
403 begin
404 for I {$ifdef FPC}:= Low(X3DKeywords) to High(X3DKeywords) {$else}in X3DKeywords{$endif} do
405 if X3DKeywordsName[I] = s then
406 begin
407 Index := I;
408 Result := true;
409 Exit;
410 end;
411 Result := false;
412 end;
413
414 { TX3DLexer ------------------------------------------------------------- }
415
416 procedure TX3DLexer.CreateCommonBegin(AStream: TPeekCharStream;
417 AOwnsStream: boolean);
418 begin
419 inherited Create;
420
421 FStream := AStream;
422 FOwnsStream := AOwnsStream;
423 end;
424
425 procedure TX3DLexer.CreateCommonEnd;
426 begin
427 { calculate VRMLWhitespaces, VRMLNoWhitespaces
428 (based on VRMLVerXxx) }
429 VRMLWhitespaces := [' ',#9, #10, #13];
430 if FVersion.Major >= 2 then
431 Include(VRMLWhitespaces, ',');
432 VRMLNoWhitespaces := AllChars - VRMLWhitespaces;
433
434 { calculate VRMLNameChars, VRMLNameFirstChars }
435 { These are defined according to vrml97specification on page 24. }
436 VRMLNameChars := AllChars -
437 [#0..#$1f, ' ', '''', '"', '#', ',', '.', '[', ']', '\', '{', '}'];
438 if FVersion.Major <= 1 then
439 VRMLNameChars := VRMLNameChars - ['(', ')', '|'];
440 if FVersion.Major >= 3 then
441 { X3D standard has a little less characters allowed.
442 In particular, ':' (unicode 0x3a) is not allowed and should not be,
443 because component statements are separated by vtColon.
444 Detailed spec is in "IdFirstChar" and "IdRestChars" on X3D classic VRML
445 spec grammat. }
446 VRMLNameChars := VRMLNameChars - [':'];
447 VRMLNameFirstChars := VRMLNameChars - ['0'..'9', '-','+'];
448
449 {read first token}
450 NextToken;
451 end;
452
453 constructor TX3DLexer.Create(AStream: TPeekCharStream; AOwnsStream: boolean);
454 const
455 InventorHeaderStart = '#Inventor ';
456
457 VRML1HeaderStart = '#VRML V1.0 ';
458 EncodingAscii = 'ascii'; { Used by VRML 1.0 }
459
460 VRML2HeaderStart = '#VRML V2.0 ';
461 { This is not an official VRML header, but it's used by VRML models on
462 [http://www.itl.nist.gov/div897/ctg/vrml/chaco/chaco.html] }
463 VRML2DraftHeaderStart = '#VRML Draft #2 V2.0 ';
464 EncodingUtf8 = 'utf8'; { Used by VRML >= 2.0 }
465
466 X3DHeaderStart = '#X3D ';
467
468 procedure Utf8HeaderReadRest(const Line: string);
469 var
470 Encoding: string;
471 begin
472 Encoding := NextTokenOnce(Line);
473 if Encoding <> EncodingUtf8 then
474 raise EX3DLexerError.Create(Self,
475 'VRML 2.0 / X3D incorrect signature: only utf8 encoding supported');
476 end;
477
478 { If Prefix is a prefix of S, then return @true and remove this prefix
479 from S. Otherwise return @false (without modifying S).
480 Allows also an UTF-8 BOM before a prefix. }
481 function CheckRemoveHeader(Prefix: string; var S: string): boolean;
482 const
483 Utf8Bom = #$EF + #$BB + #$BF;
484 begin
485 Result := IsPrefix(Prefix, S);
486 if Result then
487 Delete(S, 1, Length(Prefix)) else
488 begin
489 Prefix := Utf8Bom + Prefix;
490 Result := IsPrefix(Prefix, S);
491 if Result then
492 Delete(S, 1, Length(Prefix));
493 end;
494 end;
495
496 { Parse and remove Vmajor.minor version number from VRML header line.
497
498 Note that this is slightly more flexible than VRML / X3D classic
499 spec says (they require exactly one space before and after version
500 number, we allow any number of whitespaces). }
501 procedure ParseVersion(var S: string; out Major, Minor: Integer);
502 const
503 SIncorrectSignature = 'Inventor / VRML / X3D Incorrect signature: ';
504 Digits = ['0' .. '9'];
505 var
506 NumStart, I: Integer;
507 begin
508 I := 1;
509
510 { whitespace }
511 while SCharIs(S, I, WhiteSpaces) do Inc(I);
512
513 { "V" }
514 if not SCharIs(S, I, 'V') then
515 raise EX3DLexerError.Create(Self,
516 SIncorrectSignature + 'Expected "V" and version number');
517 Inc(I);
518
519 { major number }
520 NumStart := I;
521 while SCharIs(S, I, Digits) do Inc(I);
522 try
523 Major := StrToInt(CopyPos(S, NumStart, I - 1));
524 except
525 on E: EConvertError do
526 raise EX3DLexerError.Create(Self,
527 SIncorrectSignature + 'Incorrect major version number: ' + E.Message);
528 end;
529
530 { dot }
531 if not SCharIs(S, I, '.') then
532 raise EX3DLexerError.Create(Self,
533 SIncorrectSignature + 'Expected "." between major and minor version number');
534 Inc(I);
535
536 { minor number }
537 NumStart := I;
538 while SCharIs(S, I, Digits) do Inc(I);
539 try
540 Minor := StrToInt(CopyPos(S, NumStart, I - 1));
541 except
542 on E: EConvertError do
543 raise EX3DLexerError.Create(Self,
544 SIncorrectSignature + 'Incorrect minor version number: ' + E.Message);
545 end;
546
547 { whitespace }
548 while SCharIs(S, I, WhiteSpaces) do Inc(I);
549
550 Delete(S, 1, I - 1);
551 end;
552
553 var
554 FirstLine: AnsiString;
555 Line: String;
556 begin
557 CreateCommonBegin(AStream, AOwnsStream);
558
559 { Read first line = signature. }
560 FirstLine := Stream.ReadUpto(X3DLineTerm);
561
562 if Length(FirstLine) < 2 then
563 raise EX3DLexerError.Create(Self,
564 'Unexpected end of file on the signature line');
565
566 { Conveniently, GzipHeader doesn't contain X3DLineTerm.
567 So if Line starts with GzipHeader, we know 100% it's gzip file,
568 otherwise we know 100% it's not. }
569 if (FirstLine[1] = #$1F) and (FirstLine[2] = #$8B) then
570 raise EGzipCompressed.Create('Stream is compressed by gzip');
571
572 Line := FirstLine;
573
574 { Normal (uncompressed) VRML file, continue reading ... }
575
576 if Stream.ReadChar = -1 then
577 raise EX3DLexerError.Create(Self,
578 'Unexpected end of file on the 1st line');
579
580 { Recognize various Inventor / VRML / X3D headers,
581 code below goes chronologically through various VRML etc. versions.
582
583 For now ParseVersion is used only by X3D. But it could be used
584 also by other Inventor / VRML versions. }
585
586 if CheckRemoveHeader(InventorHeaderStart, Line) then
587 begin
588 FVersion.Major := 0;
589 FVersion.Minor := 0;
590
591 if not IsPrefix('V1.0 ascii', Line) then
592 raise EX3DLexerError.Create(Self, Format(
593 'Inventor format detected, version "%s", but only Inventor 1.0 ascii files are supported',
594 [TrimRight(Line)]));
595 end else
596 if CheckRemoveHeader(VRML1HeaderStart, Line) then
597 begin
598 FVersion.Major := 1;
599 FVersion.Minor := 0;
600
601 { then must be 'ascii';
602 VRML 1.0 'ascii' may be followed immediately by some black char. }
603 if not IsPrefix(EncodingAscii, Line) then
604 raise EX3DLexerError.Create(Self, 'Wrong VRML 1.0 signature: '+
605 'VRML 1.0 files must have "ascii" encoding');
606 end else
607 if CheckRemoveHeader(VRML2DraftHeaderStart, Line) or
608 CheckRemoveHeader(VRML2HeaderStart, Line) then
609 begin
610 FVersion.Major := 2;
611 FVersion.Minor := 0;
612 Utf8HeaderReadRest(Line);
613 end else
614 if CheckRemoveHeader(X3DHeaderStart, Line) then
615 begin
616 ParseVersion(Line, FVersion.Major, FVersion.Minor);
617 if FVersion.Major < 3 then
618 raise EX3DLexerError.Create(Self,
619 'Wrong X3D major version number, should be >= 3');
620 Utf8HeaderReadRest(Line);
621 end else
622 raise EX3DLexerError.Create(Self,
623 'VRML signature error : unrecognized signature');
624
625 CreateCommonEnd;
626 end;
627
628 constructor TX3DLexer.CreateForPartialStream(
629 AStream: TPeekCharStream; AOwnsStream: boolean;
630 const AVersion: TX3DVersion);
631 begin
632 CreateCommonBegin(AStream, AOwnsStream);
633 FVersion := AVersion;
634 CreateCommonEnd;
635 end;
636
637 constructor TX3DLexer.CreateForPartialStream(const S: string;
638 const AVersion: TX3DVersion);
639 var
640 StringStream: TStringStream;
641 begin
642 StringStream := TStringStream.Create(S);
643 CreateForPartialStream(
644 TBufferedReadStream.Create(StringStream, true), true, AVersion);
645 end;
646
647 destructor TX3DLexer.Destroy;
648 begin
649 if FOwnsStream then
650 FreeAndNil(FStream);
651 inherited;
652 end;
653
654 procedure TX3DLexer.StreamReadUptoFirstBlack(out FirstBlack: Integer);
655 begin
656 repeat
657 Stream.ReadUpto(VRMLNoWhitespaces);
658 FirstBlack := Stream.ReadChar;
659
660 { TODO: ignore X3D multiline comments also }
661
662 { ignore comments }
663 if FirstBlack = Ord('#') then
664 Stream.ReadUpto(X3DLineTerm) else
665 break;
666 until false;
667 end;
668
669 procedure TX3DLexer.ReadString;
670 var
671 endingChar: Integer;
672 NextChar: Integer;
673 begin
674 fToken := vtString;
675 fTokenString := '';
676 repeat
677 fTokenString := fTokenString + Stream.ReadUpto(['\', '"']);
678 endingChar := Stream.ReadChar;
679
680 if endingChar = -1 then
681 raise EX3DLexerError.Create(Self,
682 'Unexpected end of file in the middle of string token');
683
684 { When EndingChar is a backslash, and it is followed by " or \,
685 we ignore the 1st backslash and the next character
686 is interpreted verbatim.
687 This way \\ becomes \ and \" becomes \.
688
689 Moreover, for https://sourceforge.net/p/castle-engine/tickets/14/ ,
690 we detect (and warn) about invalid sequences after backslash,
691 and in this case we keep the backslash. }
692 if EndingChar = Ord('\') then
693 begin
694 NextChar := Stream.ReadChar;
695 if NextChar = -1 then
696 raise EX3DLexerError.Create(Self,
697 'Unexpected end of file in the middle of string token');
698 if not CharInSet(Chr(NextChar), ['"', '\']) then
699 begin
700 WritelnWarning('X3D', 'Invalid X3D file: Invalid sequence in a string: "\%s". Backslash must be followed by another backslash or double quote, for SFString and MFString (in X3D classic (VRML) encoding) and for MFString (in X3D XML encoding).',
701 [Chr(NextChar)]);
702 FTokenString := FTokenString + '\';
703 end;
704 FTokenString := FTokenString + Chr(NextChar);
705 end;
706
707 until endingChar = Ord('"');
708 end;
709
710 function TX3DLexer.NextToken: TX3DToken;
711
712 procedure ReadNameOrKeyword(FirstLetter: char);
713 {read name token. First letter has been already read.}
714 var foundKeyword: TX3DKeyword;
715 const
716 LowerCaseVKTrue = 'true' { LowerCase(X3DKeywords[vkTRUE]) };
717 LowerCaseVKFalse = 'false' { LowerCase(X3DKeywords[vkFALSE]) };
718 begin
719 fTokenName := FirstLetter +Stream.ReadUpto(AllChars - VRMLNameChars);
720
721 { teraz zobacz czy fTokenName nie jest przypadkiem keywordem. }
722 if ArrayPosX3DKeywords(fTokenName, foundKeyword) and
723 ( ( (FVersion.Major <= 1) and (foundKeyword in VRML10Keywords) ) or
724 ( (FVersion.Major = 2) and (foundKeyword in VRML20Keywords) ) or
725 ( (FVersion.Major >= 3) and (foundKeyword in X3DKeywords) )
726 ) then
727 begin
728 FToken := vtKeyword;
729 FTokenKeyword := foundKeyword;
730 end else
731 if FVersion.Major >= 3 then
732 begin
733 { In X3D XML encoding you should specify SFBool / MFBool values
734 as lower-case. From spec:
735
736 Lower-case strings for true and false are used in order
737 to maximize interoperability with other XML languages.
738
739 In my engine, I relax this rule: in *any* X3D encoding (XML, classic...),
740 you can use either lower-case or upper-case boolean values.
741 This way all valid files are handled. }
742 if FTokenName = LowerCaseVKTrue then
743 begin
744 FToken := vtKeyword;
745 FTokenKeyword := vkTRUE;
746 end else
747 if FTokenName = LowerCaseVKFalse then
748 begin
749 FToken := vtKeyword;
750 FTokenKeyword := vkFALSE;
751 end else
752 FToken := vtName;
753 end else
754 FToken := vtName;
755 end;
756
757 {
758 VRML float token corresponds to Pascal Float type,
759 in VRML it's expressed in the followin form:
760
761 @preformatted(
762 [("-"|"+")]
763 (digit+ [ "." digit+ ] | "." digit+)
764 [ "e"|"E" [("-"|"+")] digit+ ]
765 )
766
767 VRML integer token corresponds to Pascal Int64 type,
768 in VRML it's expressed in the following form:
769
770 @preformatted(
771 (form : [("-"|"+")] ("0x" digit_hex+ | [1-9]digit_decimal* | 0 digit_octal+) )
772 )
773 }
774
775 procedure ReadFloatOrInteger(FirstChar: char);
776 const
777 NoDigits = AllChars - ['0'..'9'];
778 NoHexDigits = AllChars - ['0'..'9', 'a'..'f', 'A'..'F'];
779 { TODO: octal notation not implemented (I never saw any model using it) }
780
781 procedure ReadAfterE(const AlreadyRead: string);
782 var CharAfterE: char;
783 RestOfToken: string;
784 CharAfterEInt: Integer;
785 begin
786 fToken := vtFloat;
787 { Za "e" musi byc min 1 znak, to moze byc cyfra lub - lub +.
788 Odczytujemy go do CharAfterE.
789 Potem sa juz tylko cyfry, odczytujemy je do RestOfToken.
790 (note: you can't write "Stream.ReadChar(Stream) + Stream.ReadUpto(NoDigits)"
791 because it is undefined in what order S1+S2
792 will be calculated. See console.testy/test_string_plus) }
793 CharAfterEInt := Stream.ReadChar;
794 if CharAfterEInt = -1 then
795 raise EX3DLexerError.Create(Self,
796 'Unexpected end of file in the middle of real constant');
797 CharAfterE := Chr(CharAfterEInt);
798 RestOfToken := Stream.ReadUpto(NoDigits);
799 fTokenFloat := StrToFloatDot(AlreadyRead +'e' +CharAfterE +RestOfToken);
800 end;
801
802 procedure ReadAfterDot(const AlreadyRead: string);
803 {AlreadyRead zawieraja dotychczas przeczytana liczbe calkowita ze znakiem.
804 Wiemy ze potem odczytano kropke - czytamy dalej. }
805 var s: string;
806 AfterS: integer;
807 begin
808 s := AlreadyRead +'.' +Stream.ReadUpto(NoDigits);
809 AfterS := Stream.PeekChar;
810 if (AfterS = Ord('e')) or (AfterS = Ord('E')) then
811 begin
812 Stream.ReadChar;
813 ReadAfterE(s);
814 end else
815 begin
816 fToken := vtFloat;
817 fTokenFloat := StrToFloatDot(s);
818 end;
819 end;
820
821 var Dig1, HexDig: string;
822 AfterDig1: integer;
823 begin
824 try
825 if FirstChar = '.' then
826 ReadAfterDot('') else
827 begin
828 Dig1 := FirstChar + Stream.ReadUpto(NoDigits);
829 AfterDig1 := Stream.PeekChar;
830 if (AfterDig1 = Ord('x')) and (ArrayPosStr(Dig1, ['0', '-0', '+0']) >= 0) then
831 begin
832 Stream.ReadChar; { consume AfterDig1 }
833 HexDig := Stream.ReadUpto(NoHexDigits);
834 fToken := vtInteger;
835 fTokenInteger := StrHexToInt(HexDig);
836 if Dig1[1] = '-' then fTokenInteger := - fTokenInteger;
837 end else
838 if (AfterDig1 = Ord('.')) then
839 begin
840 Stream.ReadChar; { consume AfterDig1 }
841 { w przypadku liczby postaci -.9 Dig1 byc ponizej rowne '';
842 to niczemu nie wadzi }
843 ReadAfterDot(Dig1)
844 end else
845 if (AfterDig1 = Ord('e')) or (AfterDig1 = Ord('E')) then
846 begin
847 Stream.ReadChar; { consume AfterDig1 }
848 ReadAfterE(Dig1)
849 end else
850 begin
851 { odczytalismy zwyklego integera }
852 FToken := vtInteger;
853 try
854 FTokenInteger := StrToInt64(Dig1);
855 except
856 on E: EConvertError do
857 begin
858 { We failed to use StrToInt64, but it's possibly a valid
859 float value. It's just too large for 64-bit integer... }
860 FToken := vtFloat;
861 try
862 FTokenFloat := StrToFloatDot(Dig1);
863 except
864 on EFloat: EConvertError do
865 { Raise EConvertError with nice error message,
866 explaining what we did. }
867 raise EConvertError.CreateFmt('Trying to treat "%s" as ' +
868 '64-bit integer failed (%s), trying to treat it as ' +
869 'a float also failed (%s)', [Dig1, E.Message, EFloat.Message]);
870 end;
871 end;
872 end;
873 end;
874 end;
875
876 if fToken = vtInteger then fTokenFloat := TokenInteger;
877 except
878 on E: EConvertError do raise EX3DLexerError.Create(Self, E.Message);
879 end;
880 end;
881
882 procedure RecognizeCommonTokens(FirstBlackChr: char);
883 begin
884 case FirstBlackChr of
885 '{':fToken := vtOpenCurlyBracket;
886 '}':fToken := vtCloseCurlyBracket;
887 '[':fToken := vtOpenSqBracket;
888 ']':fToken := vtCloseSqBracket;
889 '-','+','.','0'..'9':ReadFloatOrInteger(FirstBlackChr);
890 '"':ReadString;
891 else
892 if CharInSet(FirstBlackChr, VRMLNameFirstChars) then
893 ReadNameOrKeyword(FirstBlackChr) else
894 raise EX3DLexerError.Create(Self, Format('Illegal character in stream : %s (#%d)',
895 [FirstBlackChr, Ord(FirstBlackChr)]));
896 end;
897 end;
898
899 var
900 FirstBlack: integer;
901 FirstBlackChr: char;
902 begin
903 StreamReadUptoFirstBlack(FirstBlack);
904
905 if FirstBlack = -1 then
906 fToken := vtEnd else
907 begin
908 FirstBlackChr := Chr(FirstBlack);
909
910 if FVersion.Major <= 1 then
911 begin
912 case FirstBlackChr of
913 { VRML <= 1.0 symbols }
914 '(': fToken := vtOpenBracket;
915 ')': fToken := vtCloseBracket;
916 '|': fToken := vtBar;
917 ',': fToken := vtComma;
918 else RecognizeCommonTokens(FirstBlackChr);
919 end;
920 end else
921 begin
922 { It's a little unsure lexer moment here. Maybe 12.34 means
923 "token integer 12", "token dot", "token integer 34" ?
924 Well, our decisions:
925
926 1. Lexer is greedy, so if after 12 we have a dot,
927 we assume it's a float. This means that in grammar, you cannot have
928 allowed sequence integer + dot.
929
930 2. If we see a dot, then we assume it's a float if after dot we have
931 a digit. So ".12" is one token, float number. So you cannot have
932 allowed sequence dot + integer in the grammar.
933
934 It's not a problem in practice. "Dot" token is allowed only inside
935 ROUTE statements as name + dot + name (and name doesn't start with
936 digit), so it's all OK in practice. Valid VRML files may be
937 unambiguously tokenized. }
938 if (FirstBlackChr = '.') and
939 (not Between(Stream.PeekChar, Ord('0'), Ord('9'))) then
940 FToken := vtPeriod else
941 { X3D only token }
942 if ( (FirstBlackChr = ':') and (FVersion.Major >= 3) ) then
943 FToken := vtColon else
944 RecognizeCommonTokens(FirstBlackChr);
945 end;
946 end;
947
948 if LogTokens then WritelnLog('X3D lexer', DescribeToken);
949
950 result := Token;
951 end;
952
953 procedure TX3DLexer.NextTokenForceVTName;
954 var FirstBlack: integer;
955 begin
956 StreamReadUptoFirstBlack(FirstBlack);
957
958 if FirstBlack = -1 then
959 fToken := vtEnd else
960 begin
961 (* Stop tokens include { } [ ], otherwise we risk that because of this
962 hack (NextTokenForceVTName is really only a hack to try to read
963 even incorrect VRML files) we would fail to read correctly valid
964 VRML files. *)
965 fTokenName := Chr(FirstBlack) +Stream.ReadUpto(
966 VRMLWhitespaces + ['{', '}', '[', ']']);
967 fToken := vtName;
968 end;
969
970 if LogTokens then WritelnLog('X3D lexer', DescribeToken);
971
972 CheckTokenIs(vtName);
973 end;
974
975 procedure TX3DLexer.NextTokenForceVTString;
976 var FirstBlack: integer;
977 begin
978 StreamReadUptoFirstBlack(FirstBlack);
979
980 if FirstBlack = -1 then
981 fToken := vtEnd else
982 if FirstBlack = Ord('"') then
983 ReadString else
984 begin
985 fTokenString := Chr(FirstBlack) + Stream.ReadUpto(VRMLWhitespaces);
986 fToken := vtString;
987 end;
988
989 if LogTokens then WritelnLog('X3D lexer', DescribeToken);
990
991 CheckTokenIs(vtString);
992 end;
993
994 function TX3DLexer.TokenIsKeyword(const Keyword: TX3DKeyword): boolean;
995 begin
996 Result := (Token = vtKeyword) and (TokenKeyword = Keyword);
997 end;
998
999 function TX3DLexer.TokenIsKeyword(const Keywords: TX3DKeywords): boolean;
1000 begin
1001 Result := (Token = vtKeyword) and (TokenKeyword in Keywords);
1002 end;
1003
1004 function TX3DLexer.DescribeToken: string;
1005 begin
1006 Result := X3DTokenNames[Token];
1007 case Token of
1008 vtKeyword: Result := Result +' "' + X3DKeywordsName[TokenKeyword] +'"';
1009 vtName: Result := 'identifier (unquoted in X3D file) "' + TokenName +'"';
1010 vtFloat: Result := Result +' ' + FloatToStrDot(TokenFloat);
1011 vtInteger: Result := Result +' ' + IntToStr(TokenInteger);
1012 vtString: Result := Result +' "' + TokenString + '"';
1013 else ;
1014 end;
1015 end;
1016
1017 procedure TX3DLexer.CheckTokenIs(Tok: TX3DToken);
1018 begin
1019 CheckTokenIs(Tok, X3DTokenNames[Tok]);
1020 end;
1021
1022 procedure TX3DLexer.CheckTokenIs(Tok: TX3DToken; const TokDescription: string);
1023 begin
1024 if Token <> Tok then
1025 raise EX3DParserError.Create(Self, 'Expected '+TokDescription
1026 +', got '+DescribeToken);
1027 end;
1028
1029 procedure TX3DLexer.CheckTokenIs(const Toks: TX3DTokens; const ToksDescription: string);
1030 begin
1031 if not (Token in Toks) then
1032 raise EX3DParserError.Create(Self, 'Expected '+ToksDescription
1033 +', got '+DescribeToken);
1034 end;
1035
1036 procedure TX3DLexer.CheckTokenIsKeyword(const Keyword: TX3DKeyword);
1037 begin
1038 if not ( (Token = vtKeyword) and (TokenKeyword = Keyword) ) then
1039 raise EX3DParserError.Create(Self,
1040 Format('Expected keyword "%s", got %s', [X3DKeywordsName[Keyword],
1041 DescribeToken]));
1042 end;
1043
1044 function TX3DLexer.TokenX3DName: String;
1045 begin
1046 Result := DecodeX3DName(TokenName);
1047 end;
1048
1049 { Exceptions ----------------------------------------------------------------- }
1050
1051 constructor EX3DClassicReadError.Create(Lexer: TX3DLexer; const s: string);
1052 begin
1053 inherited Create(Format('Error at line %d column %d: ',
1054 [Lexer.Stream.Line, Lexer.Stream.Column]) + S);
1055 end;
1056
1057 { global funcs ------------------------------------------------------------------ }
1058
1059 function StringToX3DClassic(const s: string;
1060 const SurroundWithQuotes: boolean): string;
1061 const
1062 Patterns: array [0..1] of string = ('\', '"');
1063 PatValues: array [0..1] of string = ('\\', '\"');
1064 begin
1065 { use soMatchCase for speed }
1066 if SurroundWithQuotes then
1067 Result := '"' + SReplacePatterns(s, Patterns, PatValues, false) + '"' else
1068 Result := SReplacePatterns(s, Patterns, PatValues, false);
1069 end;
1070
1071 function StringToX3DXml(const s: string): string;
1072 const
1073 Patterns: array [0..6] of string = ('&', '"', '''', '<', '>', #10, #13);
1074 PatValues: array [0..6] of string = ('&amp;', '&quot;', '&apos;', '&lt;', '&gt;', '&#xA;', '&#xD;');
1075 begin
1076 { use soMatchCase for speed }
1077 Result := '"' + SReplacePatterns(s, Patterns, PatValues, false) + '"';
1078 end;
1079
1080 function StringToX3DXmlMulti(const s: string): string;
1081 const
1082 Patterns: array [0..7] of string = ('&', '"', '''', '<', '>', #10, #13, '\');
1083 PatValues: array [0..7] of string = ('&amp;', '\&quot;', '&apos;', '&lt;', '&gt;', '&#xA;', '&#xD;', '\\');
1084 begin
1085 { use soMatchCase for speed }
1086 Result := '"' + SReplacePatterns(s, Patterns, PatValues, false) + '"';
1087 end;
1088
1089 end.