development

토큰과 lexeme의 차이점은 무엇입니까?

big-blog 2020. 10. 16. 07:38
반응형

토큰과 lexeme의 차이점은 무엇입니까?


Aho Ullman과 Sethi의 Compiler Construction에서 소스 프로그램의 문자 입력 문자열은 논리적 의미를 갖는 일련의 문자로 나뉘어져 있으며, 토큰과 어휘로 알려진 문자열은 토큰을 구성하는 시퀀스이므로 기본적인 차이점은 무엇입니까?


Aho, Lam, Sethi 및 Ullman의 " Compilers Principles, Techniques, & Tools, 2nd Ed. " (WorldCat) 사용 , AKA the Purple Book ,

Lexeme pg. 111

어휘는 토큰의 패턴과 일치하는 소스 프로그램의 문자 시퀀스이며 어휘 분석기에서 해당 토큰의 인스턴스로 식별됩니다.

토큰 pg. 111

토큰은 토큰 이름과 선택적 속성 값으로 구성된 쌍입니다. 토큰 이름은 특정 키워드 또는 식별자를 나타내는 일련의 입력 문자와 같은 일종의 어휘 단위를 나타내는 추상 기호입니다. 토큰 이름은 구문 분석기가 처리하는 입력 기호입니다.

패턴 pg. 111

패턴은 토큰의 어휘가 취할 수있는 형식에 대한 설명입니다. 토큰으로서의 키워드의 경우 패턴은 키워드를 구성하는 문자 시퀀스 일뿐입니다. 식별자 및 일부 다른 토큰의 경우 패턴은 많은 문자열과 일치하는 더 복잡한 구조입니다.

그림 3.2 : 토큰의 예 pg. 112

[Token]       [Informal Description]                  [Sample Lexemes]
if            characters i, f                         if
else          characters e, l, s, e                   else
comparison    < or > or <= or >= or == or !=          <=, !=
id            letter followed by letters and digits   pi, score, D2
number        any numeric constant                    3.14159, 0, 6.02e23
literal       anything but ", surrounded by "'s       "core dumped"

렉서 및 파서와의이 관계를 더 잘 이해하기 위해 파서로 시작하여 입력으로 거꾸로 작업합니다.

구문 분석기를 더 쉽게 디자인하기 위해 구문 분석기는 입력으로 직접 작동하지 않고 렉서가 생성 한 토큰 목록을 가져옵니다. 우리는 그림 3.2 토큰 열 보면 토큰 등 if, else, comparison, id, numberliteral; 이것들은 토큰의 이름입니다. 일반적으로 어휘 분석기 / 파서에서 토큰은 토큰의 이름뿐만 아니라 토큰을 구성하는 문자 / 기호와 토큰을 구성하는 문자열의 시작 및 끝 위치를 포함하는 구조입니다. 오류보고, 강조 표시 등에 사용되는 시작 및 끝 위치

이제 어휘 분석기는 문자 / 기호의 입력을 받고 어휘 분석기의 규칙을 사용하여 입력 된 문자 / 기호를 토큰으로 변환합니다. 이제 렉서 / 파서로 작업하는 사람들은 자주 사용하는 것에 대해 자신 만의 단어를 가지고 있습니다. 토큰을 구성하는 일련의 문자 / 기호로 생각하는 것은 렉서 / 파서를 사용하는 사람들이 lexeme이라고 부르는 것입니다. 따라서 lexeme를 볼 때 토큰을 나타내는 일련의 문자 / 기호를 생각해보십시오. 비교 예에서 문자 / 기호의 순서는 <또는 >또는 else또는 등과 같은 다른 패턴 일 수 있습니다 3.14.

둘 사이의 관계를 생각하는 또 다른 방법은 토큰이 입력에서 문자 / 기호를 보유하는 lexeme라는 속성이있는 파서에서 사용하는 프로그래밍 구조라는 것입니다. 이제 코드에서 대부분의 토큰 정의를 살펴보면 lexeme이 토큰의 속성 중 하나로 간주되지 않을 수 있습니다. 이는 토큰이 토큰과 어휘를 나타내는 문자 / 기호의 시작 및 끝 위치를 보유 할 가능성이 더 높기 때문에 입력이 정적이기 때문에 필요에 따라 시작 및 끝 위치에서 문자 / 기호 시퀀스를 파생 할 수 있습니다.


소스 프로그램이 어휘 분석기에 입력되면 문자를 일련의 어휘로 나누는 것으로 시작됩니다. 그런 다음 lexemes는 토큰 구성에 사용되며, 여기서 lexemes는 토큰으로 매핑됩니다. myVar 라는 변수는 < id , "num">을 나타내는 토큰에 매핑됩니다. 여기서 "num"은 기호 테이블에서 변수의 위치를 ​​가리켜 야합니다.

간단히 말해서 :

  • Lexemes는 문자 입력 스트림에서 파생 된 단어입니다.
  • 토큰은 토큰 이름과 속성 값에 매핑 된 렉서입니다.


예를 들면 다음과 같습니다.
x = a + b * 2
다음과 같은 lexemes를 생성합니다. {x, =, a, +, b, *, 2}
해당 토큰 포함 : {< id , 0>, <=>, < id , 1 >, <+>, < id , 2>, <*>, < id , 3>}


a) 토큰은 프로그램의 텍스트를 구성하는 엔티티의 상징적 인 이름입니다. 예를 들어 키워드 if의 경우 if, 모든 식별자의 id. 이것들은 어휘 분석기의 출력을 구성합니다. 5

(b) 패턴은 입력의 문자 시퀀스가 ​​토큰을 구성하는시기를 지정하는 규칙입니다. 예를 들어 토큰 if에 대한 시퀀스 i, f 및 토큰 ID에 대한 문자로 시작하는 영숫자 시퀀스.

(c) 어휘는 패턴과 일치하는 입력의 문자 시퀀스입니다 (따라서 토큰의 인스턴스를 구성합니다). 예를 들어 if 패턴과 일치하고 foo123bar가 id 패턴과 일치하는 경우.


LEXEME- 토큰을 형성하는 패턴과 일치하는 문자 시퀀스

PATTERN- 토큰을 정의하는 규칙 세트

TOKEN- 프로그래밍 언어의 문자 집합 (예 : ID, 상수, 키워드, 연산자, 구두점, 리터럴 문자열)에 대한 의미있는 문자 모음


토큰 : (키워드, 식별자, 구두점 문자, 다중 문자 연산자)의 종류는 간단히 토큰입니다.

패턴 : 입력 문자에서 토큰을 형성하는 규칙입니다.

Lexeme : 토큰에 대한 패턴과 일치하는 SOURCE PROGRAM의 문자 시퀀스입니다. 기본적으로 토큰의 요소입니다.


토큰 : 토큰은 단일 논리적 엔터티로 처리 할 수있는 일련의 문자입니다. 일반적인 토큰은 다음과 같습니다.
1) 식별자
2) 키워드
3) 연산자
4) 특수 기호
5) 상수

패턴 : 동일한 토큰이 출력으로 생성되는 입력의 문자열 집합입니다. 이 문자열 세트는 토큰과 연관된 패턴이라는 규칙에 의해 설명됩니다. 어휘
: 어휘는 토큰 패턴과 일치하는 소스 프로그램의 문자 시퀀스입니다.


어휘 분석기 (Scanner라고도 함)의 작동을 살펴 보겠습니다.

예제 표현식을 보겠습니다.

INPUT : cout << 3+2+3;

FORMATTING PERFORMED BY SCANNER :  {cout}|space|{<<}|space|{3}{+}{2}{+}{3}{;} 

하지만 실제 출력이 아닙니다.

스캐너는 입력이 꺼질 때까지 소스 프로그램 텍스트에서 LEXEME을 반복적으로 찾습니다.

Lexeme은 grammar에있는 유효한 터미널 문자열을 형성하는 입력의 하위 문자열입니다. 모든 어휘 는 끝에 설명 패턴따릅니다 (독자가 마지막으로 건너 뛸 수있는 부분).

(중요한 규칙은 다음 공백이 나타날 때까지 유효한 터미널 문자열을 형성하는 가능한 가장 긴 접두사를 찾는 것입니다 ... 아래 설명)

LEXEMES :

  1. cout
  2. <<

( "<"도 유효한 터미널 문자열이지만 위에서 언급 한 규칙은 스캐너가 반환 한 토큰을 생성하기 위해 lexeme "<<"의 패턴을 선택해야합니다.)

  1. +
  2. 2
  3. ;

TOKENS : Scanner가 (유효한) lexeme을 찾을 때마다 토큰이 한 번에 하나씩 (파서가 요청하면 Scanner에 의해) 반환됩니다. 스캐너가 아직 존재하지 않는 경우 토큰 을 생성하기 위해 lexeme을 찾을 때 기호 테이블 항목 (속성 : 주로 토큰 범주 및 기타 속성 포함) 을 생성합니다.

'#'은 기호 테이블 항목을 나타냅니다. 이해의 편의를 위해 위 목록에서 lexeme 번호를 지적했지만 기술적으로는 기호 테이블의 실제 레코드 색인이어야합니다.

다음 토큰은 스캐너가 위의 예에서 지정된 순서대로 파서에 반환합니다.

  1. <식별자, # 1>

  2. <연산자, # 2>

  3. <리터럴, # 3>

  4. <연산자, # 4>

  5. <리터럴, # 5>

  6. <연산자, # 4>

  7. <리터럴, # 3>

  8. <Punctuator, # 6>

차이점을 알 수 있듯이 토큰은 입력의 하위 문자열 인 lexeme과는 달리 쌍입니다.

그리고 쌍의 첫 번째 요소는 토큰 클래스 / 카테고리입니다.

토큰 클래스는 다음과 같습니다.

  • 키워드
  • 식별자
  • 리터럴
  • 펑추 에이터
  • 운영자
  • 그리고 한 가지 더, Scanner는 공백을 감지하고이를 무시하며 공백에 대한 토큰을 전혀 형성하지 않습니다. 모든 구분 기호가 공백 인 것은 아니며 공백은 스캐너에서 목적을 위해 사용하는 구분 기호의 한 형태입니다. 입력의 탭, 줄 바꿈, 공백, 이스케이프 문자는 모두 통칭하여 공백 구분 기호라고합니다. 다른 구분 기호는 ';'입니다. ',' ':'등은 토큰을 형성하는 어휘로 널리 알려져 있습니다.

    Total number of tokens returned are 8 here , however only 6 symbol table entries are made for lexemes . Lexemes are also 8 in total ( see definition of lexeme )

    --- You can skip this part

    A ***pattern*** is a rule ( say, a regular expression ) that is used to check if a string-of-terminals is valid or not.

    If a substring of input composed only of grammar terminals is following the rule specified by any of the listed patterns , it is validated as a lexeme and selected pattern will identify the category of lexeme, else a lexical error is reported due to either (i) not following any of the rules or (ii) input consists of a bad terminal-character not present in grammar itself.

    for example :
    
    1. No Pattern Exists : In C++ , "99Id_Var" is grammar-supported string-of-terminals but is not recognised by any of patterns hence lexical error is reported .
    
    2. Bad Input Character : $,@,unicode characters may not be supported as a valid character in few programming languages.`
    

    Lexeme - A lexeme is a sequence of characters in the source program that matches the pattern for a token and is identified by the lexical analyzer as an instance of that token.

    Token - Token is a pair consisting of a token name and an optional token value. The token name is a category of a lexical unit.Common token names are

    • identifiers: names the programmer chooses
    • keywords: names already in the programming language
    • separators (also known as punctuators): punctuation characters and paired-delimiters
    • operators: symbols that operate on arguments and produce results
    • literals: numeric, logical, textual, reference literals

    Consider this expression in the programming language C:

    sum = 3 + 2;

    Tokenized and represented by the following table:

     Lexeme        Token category
    ------------------------------
    sum      |    Identifier
     =       |    Assignment operator
     3       |    Integer literal
     +       |    Addition operator
     2       |    Integer literal
     ;       |    End of statement
    

    Lexeme- A lexeme is a string of character that is the lowest level syntactic unit in the programming language.

    Token- The token is a syntactic category that forms a class of lexemes that means which class the lexeme belong is it a keyword or identifier or anything else. One of the major tasks of the lexical analyzer is to create a pair of lexemes and tokens, that is to collect all the characters.

    Let us take an example:-

    if(y<= t)

    y=y-3;

    Lexeme                      Token

    if                                       KEYWORD

    (                                 LEFT PARENTHESIS

    y                                     IDENTIFIER

    < =                                 COMPARISON

    t                                     IDENTIFIER

    )                                RIGHT PARENTHESIS

    y                                    IDENTIFIER

    =                                   ASSGNMENT

    y                                   IDENTIFIER

    _                                   ARITHMATIC

    3                                     INTEGER

    ;                                    SEMICOLON

    Relation between Lexeme and Token

    Relation between lexeme and token


    Lexeme Lexemes are said to be a sequence of characters (alphanumeric) in a token.

    Token A token is a sequence of characters that can be identified as a single logical entity . Typically tokens are keywords, identifiers, constants, strings, punctuation symbols, operators. numbers.

    Pattern A set of strings described by rule called pattern. A pattern explains what can be a token and these patterns are defined by means of regular expressions, that are associated with the token.


    Lexical Analyzer takes a sequence of characters identifies a lexeme that matches the regular expression and further categorizes it to token. Thus, a Lexeme is matched string and a Token name is the category of that lexeme.

    For example, consider below regular expression for an identifier with input "int foo, bar;"

    letter(letter|digit|_)*

    Here, foo and bar match the regular expression thus are both lexemes but are categorized as one token ID i.e identifier.

    Also note, next phase i.e syntax analyzer need not have to know about lexeme but a token.


    Lexeme is basically the unit of a token and it is basically sequence of characters that matches the token and helps to break the source code into tokens.

    For example: If the source is x=b, then the lexemes would be x, =, b and the tokens would be <id, 0>, <=>, <id, 1>.

    참고URL : https://stackoverflow.com/questions/14954721/what-is-the-difference-between-a-token-and-a-lexeme

    반응형