You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

799 lines
20 KiB

15 years ago
15 years ago
15 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
15 years ago
15 years ago
13 years ago
13 years ago
  1. /*
  2. * This program source code file is part of KiCad, a free EDA CAD application.
  3. *
  4. * Copyright (C) 2007-2013 SoftPLC Corporation, Dick Hollenbeck <dick@softplc.com>
  5. * Copyright (C) 2007-2020 KiCad Developers, see AUTHORS.txt for contributors.
  6. *
  7. * This program is free software; you can redistribute it and/or
  8. * modify it under the terms of the GNU General Public License
  9. * as published by the Free Software Foundation; either version 2
  10. * of the License, or (at your option) any later version.
  11. *
  12. * This program is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. * GNU General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU General Public License
  18. * along with this program; if not, you may find one here:
  19. * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
  20. * or you may search the http://www.gnu.org website for the version 2 license,
  21. * or you may write to the Free Software Foundation, Inc.,
  22. * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
  23. */
  24. #include <cstdarg>
  25. #include <cstdio>
  26. #include <cstdlib> // bsearch()
  27. #include <cctype>
  28. #include <dsnlexer.h>
  29. #define FMT_CLIPBOARD _( "clipboard" )
  30. //-----<DSNLEXER>-------------------------------------------------------------
  31. void DSNLEXER::init()
  32. {
  33. curTok = DSN_NONE;
  34. prevTok = DSN_NONE;
  35. stringDelimiter = '"';
  36. specctraMode = false;
  37. space_in_quoted_tokens = false;
  38. commentsAreTokens = false;
  39. curOffset = 0;
  40. #if 1
  41. if( keywordCount > 11 )
  42. {
  43. // resize the hashtable bucket count
  44. keyword_hash.reserve( keywordCount );
  45. }
  46. // fill the specialized "C string" hashtable from keywords[]
  47. const KEYWORD* it = keywords;
  48. const KEYWORD* end = it + keywordCount;
  49. for( ; it < end; ++it )
  50. {
  51. keyword_hash[it->name] = it->token;
  52. }
  53. #endif
  54. }
  55. DSNLEXER::DSNLEXER( const KEYWORD* aKeywordTable, unsigned aKeywordCount,
  56. FILE* aFile, const wxString& aFilename ) :
  57. iOwnReaders( true ),
  58. start( NULL ),
  59. next( NULL ),
  60. limit( NULL ),
  61. reader( NULL ),
  62. keywords( aKeywordTable ),
  63. keywordCount( aKeywordCount )
  64. {
  65. FILE_LINE_READER* fileReader = new FILE_LINE_READER( aFile, aFilename );
  66. PushReader( fileReader );
  67. init();
  68. }
  69. DSNLEXER::DSNLEXER( const KEYWORD* aKeywordTable, unsigned aKeywordCount,
  70. const std::string& aClipboardTxt, const wxString& aSource ) :
  71. iOwnReaders( true ),
  72. start( NULL ),
  73. next( NULL ),
  74. limit( NULL ),
  75. reader( NULL ),
  76. keywords( aKeywordTable ),
  77. keywordCount( aKeywordCount )
  78. {
  79. STRING_LINE_READER* stringReader = new STRING_LINE_READER( aClipboardTxt, aSource.IsEmpty() ?
  80. wxString( FMT_CLIPBOARD ) : aSource );
  81. PushReader( stringReader );
  82. init();
  83. }
  84. DSNLEXER::DSNLEXER( const KEYWORD* aKeywordTable, unsigned aKeywordCount,
  85. LINE_READER* aLineReader ) :
  86. iOwnReaders( false ),
  87. start( NULL ),
  88. next( NULL ),
  89. limit( NULL ),
  90. reader( NULL ),
  91. keywords( aKeywordTable ),
  92. keywordCount( aKeywordCount )
  93. {
  94. if( aLineReader )
  95. PushReader( aLineReader );
  96. init();
  97. }
  98. static const KEYWORD empty_keywords[1] = {};
  99. DSNLEXER::DSNLEXER( const std::string& aSExpression, const wxString& aSource ) :
  100. iOwnReaders( true ),
  101. start( NULL ),
  102. next( NULL ),
  103. limit( NULL ),
  104. reader( NULL ),
  105. keywords( empty_keywords ),
  106. keywordCount( 0 )
  107. {
  108. STRING_LINE_READER* stringReader = new STRING_LINE_READER( aSExpression, aSource.IsEmpty() ?
  109. wxString( FMT_CLIPBOARD ) : aSource );
  110. PushReader( stringReader );
  111. init();
  112. }
  113. DSNLEXER::~DSNLEXER()
  114. {
  115. if( iOwnReaders )
  116. {
  117. // delete the LINE_READERs from the stack, since I own them.
  118. for( READER_STACK::iterator it = readerStack.begin(); it!=readerStack.end(); ++it )
  119. delete *it;
  120. }
  121. }
  122. void DSNLEXER::SetSpecctraMode( bool aMode )
  123. {
  124. specctraMode = aMode;
  125. if( aMode )
  126. {
  127. // specctra mode defaults, some of which can still be changed in this mode.
  128. space_in_quoted_tokens = true;
  129. }
  130. else
  131. {
  132. space_in_quoted_tokens = false;
  133. stringDelimiter = '"';
  134. }
  135. }
  136. bool DSNLEXER::SyncLineReaderWith( DSNLEXER& aLexer )
  137. {
  138. // Synchronize the pointers handling the data read by the LINE_READER
  139. // only if aLexer shares the same LINE_READER, because only in this case
  140. // the char buffer is be common
  141. if( reader != aLexer.reader )
  142. return false;
  143. // We can synchronize the pointers which handle the data currently read
  144. start = aLexer.start;
  145. next = aLexer.next;
  146. limit = aLexer.limit;
  147. // Sync these parameters is not mandatory, but could help
  148. // for instance in debug
  149. curText = aLexer.curText;
  150. curOffset = aLexer.curOffset;
  151. return true;
  152. }
  153. void DSNLEXER::PushReader( LINE_READER* aLineReader )
  154. {
  155. readerStack.push_back( aLineReader );
  156. reader = aLineReader;
  157. start = (const char*) (*reader);
  158. // force a new readLine() as first thing.
  159. limit = start;
  160. next = start;
  161. }
  162. LINE_READER* DSNLEXER::PopReader()
  163. {
  164. LINE_READER* ret = 0;
  165. if( readerStack.size() )
  166. {
  167. ret = reader;
  168. readerStack.pop_back();
  169. if( readerStack.size() )
  170. {
  171. reader = readerStack.back();
  172. start = reader->Line();
  173. // force a new readLine() as first thing.
  174. limit = start;
  175. next = start;
  176. }
  177. else
  178. {
  179. reader = 0;
  180. start = dummy;
  181. limit = dummy;
  182. }
  183. }
  184. return ret;
  185. }
  186. int DSNLEXER::findToken( const std::string& tok )
  187. {
  188. KEYWORD_MAP::const_iterator it = keyword_hash.find( tok.c_str() );
  189. if( it != keyword_hash.end() )
  190. return it->second;
  191. return DSN_SYMBOL; // not a keyword, some arbitrary symbol.
  192. }
  193. const char* DSNLEXER::Syntax( int aTok )
  194. {
  195. const char* ret;
  196. switch( aTok )
  197. {
  198. case DSN_NONE:
  199. ret = "NONE";
  200. break;
  201. case DSN_STRING_QUOTE:
  202. ret = "string_quote"; // a special DSN syntax token, see specctra spec.
  203. break;
  204. case DSN_QUOTE_DEF:
  205. ret = "quoted text delimiter";
  206. break;
  207. case DSN_DASH:
  208. ret = "-";
  209. break;
  210. case DSN_SYMBOL:
  211. ret = "symbol";
  212. break;
  213. case DSN_NUMBER:
  214. ret = "number";
  215. break;
  216. case DSN_RIGHT:
  217. ret = ")";
  218. break;
  219. case DSN_LEFT:
  220. ret = "(";
  221. break;
  222. case DSN_STRING:
  223. ret = "quoted string";
  224. break;
  225. case DSN_EOF:
  226. ret = "end of input";
  227. break;
  228. default:
  229. ret = "???";
  230. }
  231. return ret;
  232. }
  233. const char* DSNLEXER::GetTokenText( int aTok )
  234. {
  235. const char* ret;
  236. if( aTok < 0 )
  237. {
  238. return Syntax( aTok );
  239. }
  240. else if( (unsigned) aTok < keywordCount )
  241. {
  242. ret = keywords[aTok].name;
  243. }
  244. else
  245. ret = "token too big";
  246. return ret;
  247. }
  248. wxString DSNLEXER::GetTokenString( int aTok )
  249. {
  250. wxString ret;
  251. ret << wxT("'") << wxString::FromUTF8( GetTokenText(aTok) ) << wxT("'");
  252. return ret;
  253. }
  254. bool DSNLEXER::IsSymbol( int aTok )
  255. {
  256. // This is static and not inline to reduce code space.
  257. // if aTok is >= 0, then it is a coincidental match to a keyword.
  258. return aTok==DSN_SYMBOL || aTok==DSN_STRING || aTok>=0;
  259. }
  260. void DSNLEXER::Expecting( int aTok )
  261. {
  262. wxString errText = wxString::Format(
  263. _( "Expecting %s" ), GetTokenString( aTok ) );
  264. THROW_PARSE_ERROR( errText, CurSource(), CurLine(), CurLineNumber(), CurOffset() );
  265. }
  266. void DSNLEXER::Expecting( const char* text )
  267. {
  268. wxString errText = wxString::Format(
  269. _( "Expecting '%s'" ), wxString::FromUTF8( text ) );
  270. THROW_PARSE_ERROR( errText, CurSource(), CurLine(), CurLineNumber(), CurOffset() );
  271. }
  272. void DSNLEXER::Unexpected( int aTok )
  273. {
  274. wxString errText = wxString::Format(
  275. _( "Unexpected %s" ), GetTokenString( aTok ) );
  276. THROW_PARSE_ERROR( errText, CurSource(), CurLine(), CurLineNumber(), CurOffset() );
  277. }
  278. void DSNLEXER::Duplicate( int aTok )
  279. {
  280. wxString errText = wxString::Format(
  281. _("%s is a duplicate"), GetTokenString( aTok ).GetData() );
  282. THROW_PARSE_ERROR( errText, CurSource(), CurLine(), CurLineNumber(), CurOffset() );
  283. }
  284. void DSNLEXER::Unexpected( const char* text )
  285. {
  286. wxString errText = wxString::Format(
  287. _( "Unexpected '%s'" ), wxString::FromUTF8( text ) );
  288. THROW_PARSE_ERROR( errText, CurSource(), CurLine(), CurLineNumber(), CurOffset() );
  289. }
  290. void DSNLEXER::NeedLEFT()
  291. {
  292. int tok = NextTok();
  293. if( tok != DSN_LEFT )
  294. Expecting( DSN_LEFT );
  295. }
  296. void DSNLEXER::NeedRIGHT()
  297. {
  298. int tok = NextTok();
  299. if( tok != DSN_RIGHT )
  300. Expecting( DSN_RIGHT );
  301. }
  302. int DSNLEXER::NeedSYMBOL()
  303. {
  304. int tok = NextTok();
  305. if( !IsSymbol( tok ) )
  306. Expecting( DSN_SYMBOL );
  307. return tok;
  308. }
  309. int DSNLEXER::NeedSYMBOLorNUMBER()
  310. {
  311. int tok = NextTok();
  312. if( !IsSymbol( tok ) && tok!=DSN_NUMBER )
  313. Expecting( "a symbol or number" );
  314. return tok;
  315. }
  316. int DSNLEXER::NeedNUMBER( const char* aExpectation )
  317. {
  318. int tok = NextTok();
  319. if( tok != DSN_NUMBER )
  320. {
  321. wxString errText = wxString::Format(
  322. _( "need a number for '%s'" ), wxString::FromUTF8( aExpectation ).GetData() );
  323. THROW_PARSE_ERROR( errText, CurSource(), CurLine(), CurLineNumber(), CurOffset() );
  324. }
  325. return tok;
  326. }
  327. /**
  328. * Function isSpace
  329. * tests for whitespace. Our whitespace, by our definition, is a subset of ASCII,
  330. * i.e. no bytes with MSB on can be considered whitespace, since they are likely part
  331. * of a multibyte UTF8 character.
  332. */
  333. static bool isSpace( char cc )
  334. {
  335. // cc is signed, so it is often negative.
  336. // Treat negative as large positive to exclude rapidly.
  337. if( (unsigned char) cc <= ' ' )
  338. {
  339. switch( (unsigned char) cc )
  340. {
  341. case ' ':
  342. case '\n':
  343. case '\r':
  344. case '\t':
  345. case '\0': // PCAD s-expression files have this.
  346. return true;
  347. }
  348. }
  349. return false;
  350. }
  351. inline bool isDigit( char cc )
  352. {
  353. return '0' <= cc && cc <= '9';
  354. }
  355. /// return true if @a cc is an s-expression separator character
  356. inline bool isSep( char cc )
  357. {
  358. return isSpace( cc ) || cc=='(' || cc==')';
  359. }
  360. /**
  361. * Function isNumber
  362. * returns true if the next sequence of text is a number:
  363. * either an integer, fixed point, or float with exponent. Stops scanning
  364. * at the first non-number character, even if it is not whitespace.
  365. *
  366. * @param cp is the start of the current token.
  367. * @param limit is the end of the current token.
  368. *
  369. * @return bool - true if input token is a number, else false.
  370. */
  371. static bool isNumber( const char* cp, const char* limit )
  372. {
  373. // regex for a float: "^[-+]?[0-9]*\\.?[0-9]+([eE][-+]?[0-9]+)?" i.e. any number,
  374. // code traversal manually here:
  375. bool sawNumber = false;
  376. if( cp < limit && ( *cp=='-' || *cp=='+' ) )
  377. ++cp;
  378. while( cp < limit && isDigit( *cp ) )
  379. {
  380. ++cp;
  381. sawNumber = true;
  382. }
  383. if( cp < limit && *cp == '.' )
  384. {
  385. ++cp;
  386. while( cp < limit && isDigit( *cp ) )
  387. {
  388. ++cp;
  389. sawNumber = true;
  390. }
  391. }
  392. if( sawNumber )
  393. {
  394. if( cp < limit && ( *cp=='E' || *cp=='e' ) )
  395. {
  396. ++cp;
  397. sawNumber = false; // exponent mandates at least one digit thereafter.
  398. if( cp < limit && ( *cp=='-' || *cp=='+' ) )
  399. ++cp;
  400. while( cp < limit && isDigit( *cp ) )
  401. {
  402. ++cp;
  403. sawNumber = true;
  404. }
  405. }
  406. }
  407. return sawNumber && cp==limit;
  408. }
  409. int DSNLEXER::NextTok()
  410. {
  411. const char* cur = next;
  412. const char* head = cur;
  413. prevTok = curTok;
  414. if( curTok == DSN_EOF )
  415. goto exit;
  416. if( cur >= limit )
  417. {
  418. L_read:
  419. // blank lines are returned as "\n" and will have a len of 1.
  420. // EOF will have a len of 0 and so is detectable.
  421. int len = readLine();
  422. if( len == 0 )
  423. {
  424. cur = start; // after readLine(), since start can change, set cur offset to start
  425. curTok = DSN_EOF;
  426. goto exit;
  427. }
  428. cur = start; // after readLine() since start can change.
  429. // skip leading whitespace
  430. while( cur<limit && isSpace( *cur ) )
  431. ++cur;
  432. // If the first non-blank character is #, this line is a comment.
  433. // Comments cannot follow any other token on the same line.
  434. if( cur<limit && *cur=='#' )
  435. {
  436. if( commentsAreTokens )
  437. {
  438. // Grab the entire current line [excluding end of line char(s)] as the
  439. // current token. The '#' character may not be at offset zero.
  440. while( limit[-1] == '\n' || limit[-1] == '\r' )
  441. --limit;
  442. curText.clear();
  443. curText.append( start, limit );
  444. cur = start; // ensure a good curOffset below
  445. curTok = DSN_COMMENT;
  446. head = limit; // do a readLine() on next call in here.
  447. goto exit;
  448. }
  449. else
  450. goto L_read;
  451. }
  452. }
  453. else
  454. {
  455. // skip leading whitespace
  456. while( cur<limit && isSpace( *cur ) )
  457. ++cur;
  458. }
  459. if( cur >= limit )
  460. goto L_read;
  461. if( *cur == '(' )
  462. {
  463. curText = *cur;
  464. curTok = DSN_LEFT;
  465. head = cur+1;
  466. goto exit;
  467. }
  468. if( *cur == ')' )
  469. {
  470. curText = *cur;
  471. curTok = DSN_RIGHT;
  472. head = cur+1;
  473. goto exit;
  474. }
  475. // Non-specctraMode, understands and deciphers escaped \, \r, \n, and \".
  476. // Strips off leading and trailing double quotes
  477. if( !specctraMode )
  478. {
  479. // a quoted string, will return DSN_STRING
  480. if( *cur == stringDelimiter )
  481. {
  482. // copy the token, character by character so we can remove doubled up quotes.
  483. curText.clear();
  484. ++cur; // skip over the leading delimiter, which is always " in non-specctraMode
  485. head = cur;
  486. while( head<limit )
  487. {
  488. // ESCAPE SEQUENCES:
  489. if( *head =='\\' )
  490. {
  491. char tbuf[8];
  492. char c;
  493. int i;
  494. if( ++head >= limit )
  495. break; // throw exception at L_unterminated
  496. switch( *head++ )
  497. {
  498. case '"':
  499. case '\\': c = head[-1]; break;
  500. case 'a': c = '\x07'; break;
  501. case 'b': c = '\x08'; break;
  502. case 'f': c = '\x0c'; break;
  503. case 'n': c = '\n'; break;
  504. case 'r': c = '\r'; break;
  505. case 't': c = '\x09'; break;
  506. case 'v': c = '\x0b'; break;
  507. case 'x': // 1 or 2 byte hex escape sequence
  508. for( i=0; i<2; ++i )
  509. {
  510. if( !isxdigit( head[i] ) )
  511. break;
  512. tbuf[i] = head[i];
  513. }
  514. tbuf[i] = '\0';
  515. if( i > 0 )
  516. c = (char) strtoul( tbuf, NULL, 16 );
  517. else
  518. c = 'x'; // a goofed hex escape sequence, interpret as 'x'
  519. head += i;
  520. break;
  521. default: // 1-3 byte octal escape sequence
  522. --head;
  523. for( i=0; i<3; ++i )
  524. {
  525. if( head[i] < '0' || head[i] > '7' )
  526. break;
  527. tbuf[i] = head[i];
  528. }
  529. tbuf[i] = '\0';
  530. if( i > 0 )
  531. c = (char) strtoul( tbuf, NULL, 8 );
  532. else
  533. c = '\\'; // a goofed octal escape sequence, interpret as '\'
  534. head += i;
  535. break;
  536. }
  537. curText += c;
  538. }
  539. else if( *head == '"' ) // end of the non-specctraMode DSN_STRING
  540. {
  541. curTok = DSN_STRING;
  542. ++head; // omit this trailing double quote
  543. goto exit;
  544. }
  545. else
  546. curText += *head++;
  547. } // while
  548. // L_unterminated:
  549. wxString errtxt( _( "Un-terminated delimited string" ) );
  550. THROW_PARSE_ERROR( errtxt, CurSource(), CurLine(), CurLineNumber(),
  551. cur - start + curText.length() );
  552. }
  553. }
  554. else // is specctraMode, tests in this block should not occur in KiCad mode.
  555. {
  556. /* get the dash out of a <pin_reference> which is embedded for example
  557. like: U2-14 or "U2"-"14"
  558. This is detectable by a non-space immediately preceeding the dash.
  559. */
  560. if( *cur == '-' && cur>start && !isSpace( cur[-1] ) )
  561. {
  562. curText = '-';
  563. curTok = DSN_DASH;
  564. head = cur+1;
  565. goto exit;
  566. }
  567. // switching the string_quote character
  568. if( prevTok == DSN_STRING_QUOTE )
  569. {
  570. static const wxString errtxt( _("String delimiter must be a single character of ', \", or $"));
  571. char cc = *cur;
  572. switch( cc )
  573. {
  574. case '\'':
  575. case '$':
  576. case '"':
  577. break;
  578. default:
  579. THROW_PARSE_ERROR( errtxt, CurSource(), CurLine(), CurLineNumber(), CurOffset() );
  580. }
  581. curText = cc;
  582. head = cur+1;
  583. if( head<limit && !isSep( *head ) )
  584. {
  585. THROW_PARSE_ERROR( errtxt, CurSource(), CurLine(), CurLineNumber(), CurOffset() );
  586. }
  587. curTok = DSN_QUOTE_DEF;
  588. goto exit;
  589. }
  590. // specctraMode DSN_STRING
  591. if( *cur == stringDelimiter )
  592. {
  593. ++cur; // skip over the leading delimiter: ",', or $
  594. head = cur;
  595. while( head<limit && !isStringTerminator( *head ) )
  596. ++head;
  597. if( head >= limit )
  598. {
  599. wxString errtxt( _( "Un-terminated delimited string" ) );
  600. THROW_PARSE_ERROR( errtxt, CurSource(), CurLine(), CurLineNumber(), CurOffset() );
  601. }
  602. curText.clear();
  603. curText.append( cur, head );
  604. ++head; // skip over the trailing delimiter
  605. curTok = DSN_STRING;
  606. goto exit;
  607. }
  608. } // specctraMode
  609. // non-quoted token, read it into curText.
  610. curText.clear();
  611. head = cur;
  612. while( head<limit && !isSep( *head ) )
  613. curText += *head++;
  614. if( isNumber( curText.c_str(), curText.c_str() + curText.size() ) )
  615. {
  616. curTok = DSN_NUMBER;
  617. goto exit;
  618. }
  619. if( specctraMode && curText == "string_quote" )
  620. {
  621. curTok = DSN_STRING_QUOTE;
  622. goto exit;
  623. }
  624. curTok = findToken( curText );
  625. exit: // single point of exit, no returns elsewhere please.
  626. curOffset = cur - start;
  627. next = head;
  628. return curTok;
  629. }
  630. wxArrayString* DSNLEXER::ReadCommentLines()
  631. {
  632. wxArrayString* ret = 0;
  633. bool cmt_setting = SetCommentsAreTokens( true );
  634. int tok = NextTok();
  635. if( tok == DSN_COMMENT )
  636. {
  637. ret = new wxArrayString();
  638. do
  639. {
  640. ret->Add( FromUTF8() );
  641. }
  642. while( ( tok = NextTok() ) == DSN_COMMENT );
  643. }
  644. SetCommentsAreTokens( cmt_setting );
  645. return ret;
  646. }