Compilation and interpretation
도입됨
13:59
리소스, 컴파일러 및 RPN
브라우저, 음악 플레이어, 게임을 엽니다. 프로세서는 하나 — 혹은 몇 개의 코어가 있을 뿐 — 이지만 모두 동시에 실행되는 것 같습니다. 그리고 그들은 모두 더 많은 자원을 원합니다…
영어 내레이션 · 영어와 중국어 자막 전환 가능
이 수업의 내용
| English | 의미 |
|---|---|
| guidance software | Programs that control the direction and movement of a vehicle. |
| programmer | A person who writes and develops computer programs. |
| compiler/kəmˈpaɪlə/ | 컴파일러 |
| interpreter/ɪnˈtɜːprɪtə/ | 인터프리터 |
| executable file | A file containing a program that a computer can run. |
| source/sɔːs/ | The original program instructions written by a programmer in a programming language. |
| statement/ˈsteɪtmənt/ | A line of code that tells a program what to do. |
| types/taɪps/ | Categories that describe what kind of data values can be stored or used. |
| memory/ˈmeməri/ | The part of a computer that holds data and programs currently in use. |
| Lexical analysis/ˈleksɪkl əˈnæləsɪs/ | The process of grouping source code characters into tokens and removing unnecessary whitespace and comments. |
| characters/ˈkærɪktəz/ | A text unit such as a letter, digit, punctuation mark or other symbol. |
| tokens/ˈtəʊkənz/ | 토큰 |
| keywords/ˈkiːwɜːdz/ | Words with special meanings that are part of a programming language. |
| identifiers | Names chosen by programmers for parts of a program. |
| operators/ˈɒpəreɪtəz/ | Symbols or keywords specifying operations to perform on values or expressions. |
| literals | Fixed values written directly in source code. |
| Whitespace/ˈwaɪtspeɪs/ | Spaces and other characters used to separate parts of source code. |
| comments/ˈkɒments/ | Explanatory text in source code or markup that does not execute as a program instruction. |
| symbol table/ˈsɪmbl ˈteɪbl/ | A compiler data structure recording identifiers and information such as their types, scopes or locations. |
| assignment/əˈsaɪnmənt/ | Storing a value in a variable or other named location. |
| lexer/ˈleksə/ | The part of a compiler that groups source code characters into tokens. |
| Syntax analysis/ˈsɪntæks əˈnæləsɪs/ | The process of checking tokens against language grammar and building a tree of their structure. |
| syntax/ˈsɪntæks/ | The rules that determine the correct structure of statements in a programming language. |
| grammar/ˈɡræmə/ | Rules defining valid sequences of symbols in a programming language. |
| abstract syntax tree/ˈæbstrækt ˈsɪntæks triː/ | 추상 구문 트리 |
| syntax error/ˈsɪntæks ˈerə/ | 문법 오류 |
| parser/ˈpɑːsə/ | The part of a compiler that checks syntax and builds a tree showing program structure. |
| Semantic analysis/səˈmæntɪk əˈnæləsɪs/ | Checking that a program follows meaning rules, such as using compatible types. |
| variable/ˈveərɪəbl/ | A quantity or named value that can change or take different values. |
| function/ˈfʌŋkʃn/ | A mapping that assigns exactly one output to each allowed input. |
| arguments/ˈɑːɡjuːmənts/ | Values or references supplied to a function or procedure when it is called. |
| semantics/səˈmæntɪks/ | The meaning of program statements according to the rules of a programming language. |
| Code generation/kəʊd ˌdʒenəˈreɪʃn/ | The process of producing machine code from the program's analysed structure. |
| target machine code | Instructions produced for the computer or processor that will run the program. |
| registers/ˈredʒɪstəz/ | A small, fast storage location within a processor used to hold data, addresses or instructions temporarily. |
| Code optimisation/kəʊd ˌɒptɪmaɪˈzeɪʃn/ | Improving code so it runs faster or uses less space without changing what it does. |
| constant expressions | Calculations made entirely from fixed values that can be worked out before a program runs. |
| compile time | The period when source code is translated into a form a computer can run. |
| instructions/ɪnˈstrʌkʃnz/ | Commands that tell a computer what actions to perform. |
| pipeline/ˈpaɪplaɪn/ | An arrangement that overlaps stages of different instructions or tasks to improve overall throughput. |
| stand-alone executable | A program file that can run without the compiler being present. |
| operand/ˈɒpərænd/ | A value, register or memory location that an instruction operates on. |
| logic error/ˈlɒdʒɪk ˈerə/ | A mistake in an algorithm or program that produces an incorrect result despite valid syntax. |
| testing/ˈtestɪŋ/ | Running a program with chosen inputs to check that it gives the expected outputs. |
| semantic error | An error where code follows grammar rules but breaks meaning rules, such as using incompatible types. |
콤마 하나로 발견된 우주선 손실 버그
- NASA의 마이너 1은 발사 후 293초 만에 1962에서 파괴되었습니다. 이 실패는Often Guidance 소프트웨어의 단일 오류 문자로 인해 발생했다고 비판받습니다.
- 이 이야기가 자주 재인용되는 이유는 모든 프로그래머가 아는 공포이기 때문입니다: 당신이 의도하지 않은 내용을 작성한 프로그램을 컴파일러가 기꺼이 번역하는 것.
- 컴파일러는 하나의 프로세스가 아니라 5개이며, 각 단계는 서로 다른 종류의 실수를 포착합니다. 어떤 단계가 무엇을 포착하는지 알면 특정 오류의 출처를 파악할 수 있습니다.
- 이 수업은 인터프리터가 아무것도 생성하지 않고 프로그램을 실행하는 방식과 컴파일러가 거치는 5단계에 대한 것입니다.

인터프리터가 프로그램을 실행하는 방법
- 인터프리터는 소스 코드를 동시에 번역하고 실행하여 문장 단위로 처리합니다.
- 각 문장에 대해 줄을 읽고 분석하며, 타입을 확인한 후 즉시 동작을 실행하고 다음으로 이동합니다.
- 실행 가능한 파일을 생성하지 않습니다: 번역본은 메모리 내에 존재할 뿐이며 버려집니다. 이것이 커리큘럼의 정확한 지점입니다. 즉, 번역된 버전 없이도 프로그램을 실행할 수 있다는 점입니다.
- It reports an error the moment it reaches the offending line and usually stops, which gives quick feedback while developing. Every run re-translates, so it is slower, and both the source and the interpreter must be present.

한 번 번역하고 유지하거나, 번역하여 실행하고 잊어버림

An interpreter:
난이도 1/5 · 100코인 + 오늘 첫 완료 시 작은 보너스 추가
It works line by line, reporting errors as it reaches them; nothing is saved as an executable, and it is generally slower.
An interpreter can execute a program without producing a translated version of it.
난이도 1/5 · 100코인 + 오늘 첫 완료 시 작은 보너스 추가
The translation exists only in memory, statement by statement, and is discarded. That is why the interpreter must be present every time the program runs.
1단계:.lexical analysis(어휘 분석)
- **어휘 분석(lexical analysis)**은 소스의 개별 문자들을 **토큰(tokens)**으로 묶습니다: 키워드, 식별자, 연산자 및 리터럴.
- 공백과 주석은 버려집니다. 컴파일러에게 의미 없기 때문이며, 식별자는 심볼 테이블에 등록됩니다.
- So
total ← count * 2becomes the token sequence identifier, assignment, identifier, operator, literal. The lexer does not know or care whether that makes sense.

Lexical analysis (the lexer) turns:
난이도 1/5 · 100코인 + 오늘 첫 완료 시 작은 보너스 추가
The lexer groups characters into tokens and discards whitespace/comments; parsing then builds the tree.
Lexical analysis groups the source characters into ____ and discards whitespace and comments.
난이도 1/5 · 100코인 + 오늘 첫 완료 시 작은 보너스 추가
Keywords, identifiers, operators and literals. The lexer makes no judgement about whether the sequence is a valid program.
2단계: 구문 분석(syntax analysis)
- 구문 분석(syntax analysis), 또는 파싱(parsing), 톤 순서가 언어의 **문법(grammar)**에 부합하는지 확인하고 구조를 나타내는 **추상 구문 트리(abstract syntax tree)**를 구성합니다.
- 괄호 누락,
ENDIF부재 또는 잘못된 위치에 있는 키워드는 여기서 검출됩니다. 이것이 구문 오류이며, 컴파일러가 프로그램을 행하지 않고도 이를 보고할 수 있는 이유입니다.

파서(parsing)가 검증하는 문법

3단계: 의미 분석(semantic analysis)
- **의미 분석(semantic analysis)**는 구문적으로 유효한 프로그램이 실제로 의미가 있는지 확인합니다: 변수는 사용 전에 선언되어야 하며, 대입 양측의 타입은 호환되어야 하며, 함수는 올바른 개수의 인자로 호출되어야 합니다.
total ← "seven" * 2는 완벽한 구문이지만 완전한 무의미입니다. 오직 이 단계만이 이를 포착합니다.- 이것이 시험에서 테스트하는 차이점입니다: 구문(form)은 형태이고, 의미(meaning)는 뜻입니다.

Which of these is checked by semantic analysis rather than syntax analysis?
난이도 1/5 · 100코인 + 오늘 첫 완료 시 작은 보너스 추가
Brackets are grammar, so syntax; whitespace is the lexer; registers are code generation. Declarations and types are meaning.
4단계와 5단계: 코드 생성 및 최적화(code generation and optimisation)
- **코드 생성(code generation)**은 트리를 탐색하여 타겟 기계어를 출력하며, 레지스터를 선택하고 데이터를 배치합니다.
- **코드 최적화(code optimisation)**은 기능은 바꾸지 않고 코드를 개선합니다: 중복 작업을 제거하고, 상수 표현식을 컴파일 타임에 계산하며, 파이프라인에 맞춰 명령어를 재배열합니다.
- 출력은 **독립적인 실행 가능한 파일(stand-alone executable)**로, 컴파일러가 없어도 실행됩니다.

5단계, 그리고 각 단계가 이전 단계가 잡지 못한 것을 포착함

The phases of compilation
Step through what a compiler does to your source. Each phase hands its output to the next — characters become tokens, tokens become a tree, the tree becomes optimised machine code.
Match each compiler phase to what it does.
난이도 2/5 · 140코인 + 오늘 첫 완료 시 작은 보너스 추가
Each phase transforms the program a step further: tokens, then a tree, then checked, then optimised code.
Put the compiler stages in order.
난이도 3/5 · 200코인 + 오늘 첫 완료 시 작은 보너스 추가
Lexical → syntax → semantic → code generation → optimisation.
Code optimisation aims to:
난이도 1/5 · 100코인 + 오늘 첫 완료 시 작은 보너스 추가
Optimisation improves the generated code (constant folding, removing redundancy, reordering for the pipeline).
풀이 예제: 어떤 단계가 어떤 오류를 포착하는가
x ← 5 +: 톤이 문법에 맞지 않으며, 우피연산자가 없는 연산자가 있으므로 **구문 분석(syntax analysis)**입니다.x ← y + 1에서y이 절대 선언되지 않았음: 형태는 괜찮지만 뜻이 아니므로 **의미 분석(semantic analysis)**입니다.IF a > b THEN OUTPUT a에ENDIF이 없음: 다시 **구문 분석(syntax analysis)**입니다.- 실행되어 잘못된 평균을 출력하는 프로그램: 어느 단계도 포착하지 못함. 이것은 로직 오류이며, 테스트를 통해만 찾을 수 있습니다. 해당 단계를 명칭하고 이전 단계들이 이를 통과시킨 이유를 설명하시오.

Match each faulty line to the compiler stage that catches it.
난이도 2/5 · 140코인 + 오늘 첫 완료 시 작은 보너스 추가
Syntax is form, semantics is meaning, and a logic error is valid in both but wrong in intent.
풀이 예제: 두 번역기 비교
- 컴파일러와 인터프리터가 프로그램을 처리하는 방식의 차이 2가지를 서술하시오. [4]
- 컴파일러는 실행하기 전에 전체 프로그램을 번역하여 **실행 가능한 파일(executable)**을 생성하므로, 컴파일러가 없을 때도 실행됩니다; 인터프리터는 문장 단위로 번역하고 실행하며, 실행 가능한 파일을 생성하지 않음으로, 인터프리터가 매 실행 시 필요합니다.
- 컴파일러는 번역 후 모든 오류를 함께 보고합니다. 인터프리터는 해당 줄에 도달했을 때 첫 번째 오류를 보고하고 즉시 정지합니다.
- 각 채점은 한 쌍(pairing)입니다: 하나가 하는 것과 다른 것이 하는 것을 말하시오.
놓칠 수 있는 점
- 인터프리터는 번역된 버전을 생성하지 않습니다. 이것이 교육과정에 사용된 표현이며, 점수를 부여하는 기준입니다.
- 레렉서(lexer)는 **토큰(tokens)**을 생성하고 공백과 주석을 버립니다. 프로그램이 유효한지 체크하지 않습니다.
- **구문(syntax)**은 형태(form)이고, **의미(semantic)**는 뜻(meaning)입니다. 미선언된 변수는 구문 오류가 아닌 의미 오류입니다.
- 최적화는 **프로그램이 하는 일(what the program does)**을 바꾸어서는 안 되며, 오직 빠르거나 간결하게 하는 방법만 바꿀 수 있습니다.
이해했습니다
- **인터프리터(interpreter)**는 문장 단위로 번역하고 실행하며, 실행 가능한 파일을 생성하지 않으며, 첫 번째 오류를 해당 줄에서 보고하며, 모든 실행 시 재번역합니다
- 어휘 분석은 토큰을 생성하고 공백과 주석을 제거하며, 구문 분석은 문법을 확인하고 추상 구문 트리를 구축하여 구문 오류를 포착합니다.
- 의미 분석은 의미를 검증합니다: 선언, 타입, 인자 개수 등
- 코드 생성은 기계어를 출력하고 최적화는 동작을 변경하지 않고 코드를 개선하여 독립 실행 파일을 만듭니다.
어떤 문제가 있었나요? 사이트 팀만 이 내용을 볼 수 있습니다.