Bourne-AgainShell(Bash)-as-a-Interpreter
EVA
윤주환
세 줄 요약
 인터프리터의 역할
 인터프리터의 종류
 인터프리터의 구조
Agenda
 Introduction
 Interpreter
 vs. Compiler
 Variations
 Interpreter Design
 Bash
Agenda
 Introduction
 Interpreter
 vs. Compiler
 Variations
 Interpreter Design
 Bash
Introduction
 Levels of Abstraction in Computing
Natural Language
Application Area
Programming Language
Compiler/Interpreter
Operating System
Machine Language
Introduction
Introduction
https://www.immi.gov.au/living-in-australia/help-with-english/NIS/Interpreter_Symbol.jpg
Interpreter
Agenda
 Introduction
 Interpreter
 vs. Compiler
 Variations
 Interpreter Design
 Bash
Interpreter
 “In computer science, an interpreter is a computer program that
directly executes” via Wikipedia/Interpreter(computing)
인터프리터는 컴퓨터 프로그램을 직접 실행하는 프로그램
 Parse the source code and perform its behavior directly
소스코드를 분석하여 그 동작을 수행한다.
 Translate source code into some efficient intermediate
representation and immediately execute this
소스코드를 (효율적인) 중간 표현으로 변환하여 실행한다.
 Explicitly execute stored precompiled code made by a compiler
which is part of the interpreter system
인터프리터 시스템에서 컴파일러가 미리 컴파일한 코드를 실행한다.
Agenda
 Introduction
 Interpreter
 vs. Compiler
 Variations
 Interpreter Design
 Bash
Interpreter vs. Compiler
 Interpreter
 Compiler
구문 분석 문맥 체크 입/출력 처리 명령 수행
입력 출력
구문 분석 문맥 체크 코드 최적화 코드 생성
Agenda
 Introduction
 Interpreter
 vs. Compiler
 Variations
 Interpreter Design
 Bash
Interpreter Variations
 Bytecode(Intermediate-code) interpreters
 Abstract Syntax Tree interpreters
 Just-in-time compilation
 Self-interpreter
Interpreter Variations
 Bytecode(Intermediate-code) interpreters
 Intermediate Code isn’t tied to any particular hardware
Source
Code
Compile
Inter-
mediate
Code
ProgramExecute
Interpreter Variations
 Abstract Syntax Tree interpreters
Source
Code
Transform
(Optimized)
Abstract
Syntax
Tree
ProgramExecute
Interpreter Variations
 Abstract Syntax Tree interpreters
From: https://www.cs.umd.edu/class/spring2005/cmsc433/p3/
Interpreter Variations
 Just-in-time compilation
Source
Code
Compile
Inter-
mediate
Code
(Optimized)
Inter-
mediate
Code
Execute
JIT Compile
Interpreter Variations
 Self-interpreter
 C로 만든 C 컴파일러, Python으로 만든 Python 인터프리터…
 See Meta-circular evaluator
def python_interpreter(code):
exec code
Agenda
 Introduction
 Interpreter
 vs. Compiler
 Variations
 Interpreter Design
 Bash
Interpreter Design
구문 분석 문맥 체크 입/출력 처리 명령 수행
입력 출력
Lexical
Analysis
구문 분석
Grammar
Syntactic
Analysis
문법 체크
Syntax
I/O
Processing
입/출력처리
Command
Execution
명령 수행
입력 출력
Semantic
Analysis
문맥 체크
Type
Interpreter Design
 Lexical Analysis (Lexer/Scanner)
 Automata
 Token 생성
 {Type, Contents}
int a = n * 5; [TYPE: int]
[ID: a]
[ASSIGN]
[ID: n]
[MULT]
[CONST: 5]
[SEMICOLON]
Interpreter Design
 Syntactic Analysis (Syntactic Analyzer/Parser)
 BNF (Backus-Naur Form) 에 의해 Syntax Tree 생성
 Formula → Assignment
 Assignment → Variable EQ Expression
 Variable → TYPE ID | ID
 Expression → Elem OP Elem
 Elem → ID | CONST
 OP → + | - | * | /
 ID → a | b | c | … | z
 CONST → 0 | 1 | 2| … | 9
 Symbol Table 생성
int a = n * 5;
Formula
Assignment
Variable
TYPE Elem
EQ Expression
Elem ElemOP
int ID ID CONST*
a n 5
Interpreter Design
 Semantic Analysis (Type Checker)
 앞의 두 단계에서 생성한 Symbol Table에 Type 등의 정보를 추가
 Syntax Tree에서 특정 변수와 연결된 변수 또는 상수의 타입이
Symbol Table에 있는 정보와 다른지 확인
Interpreter Design
 나머지는 I/O 처리 및 실행
 via System Call
Agenda
 Introduction
 Interpreter
 vs. Compiler
 Variations
 Interpreter Design
 Bash
Bash – The Bourne-Again Shell
 Bourne Shell(sh)의 후계자
 리눅스를 비롯한 대부분의 유닉스 시스템에서
가장 보편적으로 사용되는 쉘
 GPLv3+ (http://www.gnu.org/software/bash/)
Bash Shell Script
 $ NAME=Juhwan
 $ echo “Hello, $NAME”
Hello, Juhwan
 $ if [[ "x$NAME" != "x" ]]; then echo "Anybody there?“; fi
Anybody there?
 $ for N in {1..5}; do echo “Line #$N”; done
Line #1
Line #2
Line #3
Line #4
Line #5
Bash Component Architecture
Input
Lexical Analysis
and Parsing
Expansion
Command
Execution
Exit Status
Brace
Expansion
Variable and
Parameter
Expansion,
Command
Process,
Arithmetic
Substitution
Expansion Expansion
Tilde
Expansion
Input Processing
“Sequence of Charactersn”
Input Processing
 GNU Readline
 줄 편집 및 입력 기록 저장 등의 역할을 하는 라이브러리
 입력 자동 완성, 커서 이동, 잘라내기, 복사, 붙여 넣기 등 지원
Read
Dispatch
Execute
Re-display
키보드 또는
매크로 입력
키-인덱스
테이블 생성
키 입력 반영 &
App 실행 결과
표시
입력을 통해
App 호출
Expansion
{1..5} 1 2 3 4 5Brace expansion
~/workspace
/home/juhwan/
workspace
Tilde expansion
$OSTYPE “linux-gnu”Variable expansion
Word Splitting
 Internel Field Seperator (IFS)
 IFS=$' tn' (in env. variable)
 Expansion 수행 후 하나 이상의 단어로 변환
Command Execution
 POSIX에서는 단순하게 명령을 호출하도록 정하고 있음
 명령에 인자들을 끼워서 전달
 ex) gcc –Wall –o a a.c
 리다이렉션
 Parser에서 File descriptor(fd)를 복사하는 형태로 전달
 빌트인 명령
 별도 프로세스를 만들지 않고 자체 실행
 작업 제어
 { PID, state, return }
 Foreground, Background
Bash-as-a-Interpreter

Bash-as-a-Interpreter

  • 1.
  • 2.
    세 줄 요약 인터프리터의 역할  인터프리터의 종류  인터프리터의 구조
  • 3.
    Agenda  Introduction  Interpreter vs. Compiler  Variations  Interpreter Design  Bash
  • 4.
    Agenda  Introduction  Interpreter vs. Compiler  Variations  Interpreter Design  Bash
  • 5.
    Introduction  Levels ofAbstraction in Computing Natural Language Application Area Programming Language Compiler/Interpreter Operating System Machine Language
  • 6.
  • 7.
  • 8.
    Agenda  Introduction  Interpreter vs. Compiler  Variations  Interpreter Design  Bash
  • 9.
    Interpreter  “In computerscience, an interpreter is a computer program that directly executes” via Wikipedia/Interpreter(computing) 인터프리터는 컴퓨터 프로그램을 직접 실행하는 프로그램  Parse the source code and perform its behavior directly 소스코드를 분석하여 그 동작을 수행한다.  Translate source code into some efficient intermediate representation and immediately execute this 소스코드를 (효율적인) 중간 표현으로 변환하여 실행한다.  Explicitly execute stored precompiled code made by a compiler which is part of the interpreter system 인터프리터 시스템에서 컴파일러가 미리 컴파일한 코드를 실행한다.
  • 10.
    Agenda  Introduction  Interpreter vs. Compiler  Variations  Interpreter Design  Bash
  • 12.
    Interpreter vs. Compiler Interpreter  Compiler 구문 분석 문맥 체크 입/출력 처리 명령 수행 입력 출력 구문 분석 문맥 체크 코드 최적화 코드 생성
  • 13.
    Agenda  Introduction  Interpreter vs. Compiler  Variations  Interpreter Design  Bash
  • 14.
    Interpreter Variations  Bytecode(Intermediate-code)interpreters  Abstract Syntax Tree interpreters  Just-in-time compilation  Self-interpreter
  • 15.
    Interpreter Variations  Bytecode(Intermediate-code)interpreters  Intermediate Code isn’t tied to any particular hardware Source Code Compile Inter- mediate Code ProgramExecute
  • 16.
    Interpreter Variations  AbstractSyntax Tree interpreters Source Code Transform (Optimized) Abstract Syntax Tree ProgramExecute
  • 17.
    Interpreter Variations  AbstractSyntax Tree interpreters From: https://www.cs.umd.edu/class/spring2005/cmsc433/p3/
  • 18.
    Interpreter Variations  Just-in-timecompilation Source Code Compile Inter- mediate Code (Optimized) Inter- mediate Code Execute JIT Compile
  • 19.
    Interpreter Variations  Self-interpreter C로 만든 C 컴파일러, Python으로 만든 Python 인터프리터…  See Meta-circular evaluator def python_interpreter(code): exec code
  • 20.
    Agenda  Introduction  Interpreter vs. Compiler  Variations  Interpreter Design  Bash
  • 21.
    Interpreter Design 구문 분석문맥 체크 입/출력 처리 명령 수행 입력 출력 Lexical Analysis 구문 분석 Grammar Syntactic Analysis 문법 체크 Syntax I/O Processing 입/출력처리 Command Execution 명령 수행 입력 출력 Semantic Analysis 문맥 체크 Type
  • 22.
    Interpreter Design  LexicalAnalysis (Lexer/Scanner)  Automata  Token 생성  {Type, Contents} int a = n * 5; [TYPE: int] [ID: a] [ASSIGN] [ID: n] [MULT] [CONST: 5] [SEMICOLON]
  • 23.
    Interpreter Design  SyntacticAnalysis (Syntactic Analyzer/Parser)  BNF (Backus-Naur Form) 에 의해 Syntax Tree 생성  Formula → Assignment  Assignment → Variable EQ Expression  Variable → TYPE ID | ID  Expression → Elem OP Elem  Elem → ID | CONST  OP → + | - | * | /  ID → a | b | c | … | z  CONST → 0 | 1 | 2| … | 9  Symbol Table 생성 int a = n * 5; Formula Assignment Variable TYPE Elem EQ Expression Elem ElemOP int ID ID CONST* a n 5
  • 24.
    Interpreter Design  SemanticAnalysis (Type Checker)  앞의 두 단계에서 생성한 Symbol Table에 Type 등의 정보를 추가  Syntax Tree에서 특정 변수와 연결된 변수 또는 상수의 타입이 Symbol Table에 있는 정보와 다른지 확인
  • 25.
    Interpreter Design  나머지는I/O 처리 및 실행  via System Call
  • 26.
    Agenda  Introduction  Interpreter vs. Compiler  Variations  Interpreter Design  Bash
  • 27.
    Bash – TheBourne-Again Shell  Bourne Shell(sh)의 후계자  리눅스를 비롯한 대부분의 유닉스 시스템에서 가장 보편적으로 사용되는 쉘  GPLv3+ (http://www.gnu.org/software/bash/)
  • 28.
    Bash Shell Script $ NAME=Juhwan  $ echo “Hello, $NAME” Hello, Juhwan  $ if [[ "x$NAME" != "x" ]]; then echo "Anybody there?“; fi Anybody there?  $ for N in {1..5}; do echo “Line #$N”; done Line #1 Line #2 Line #3 Line #4 Line #5
  • 29.
    Bash Component Architecture Input LexicalAnalysis and Parsing Expansion Command Execution Exit Status Brace Expansion Variable and Parameter Expansion, Command Process, Arithmetic Substitution Expansion Expansion Tilde Expansion
  • 30.
  • 31.
    Input Processing  GNUReadline  줄 편집 및 입력 기록 저장 등의 역할을 하는 라이브러리  입력 자동 완성, 커서 이동, 잘라내기, 복사, 붙여 넣기 등 지원 Read Dispatch Execute Re-display 키보드 또는 매크로 입력 키-인덱스 테이블 생성 키 입력 반영 & App 실행 결과 표시 입력을 통해 App 호출
  • 32.
    Expansion {1..5} 1 23 4 5Brace expansion ~/workspace /home/juhwan/ workspace Tilde expansion $OSTYPE “linux-gnu”Variable expansion
  • 33.
    Word Splitting  InternelField Seperator (IFS)  IFS=$' tn' (in env. variable)  Expansion 수행 후 하나 이상의 단어로 변환
  • 34.
    Command Execution  POSIX에서는단순하게 명령을 호출하도록 정하고 있음  명령에 인자들을 끼워서 전달  ex) gcc –Wall –o a a.c  리다이렉션  Parser에서 File descriptor(fd)를 복사하는 형태로 전달  빌트인 명령  별도 프로세스를 만들지 않고 자체 실행  작업 제어  { PID, state, return }  Foreground, Background

Editor's Notes

  • #6 컴퓨텅의 추상화(계층 별 연결) 단계
  • #7 공통점? 인터프리터 언어들. 물론 이게 인터프리터 언어의 전부는 아니지만…
  • #8 오스트레일리아 연방, 주, 지역 정부에서 승인한 국가 공공 정보 서비스로, 영어를 잘 못하는 사람들에게 언어 지원을 제공한다.
  • #10 중간 표현으로 변환하는 과정은 컴파일러가 수행 참고: 세번째 항목의 관점에서는 CPU도 인터프리터라고 볼 수 있다.
  • #13 기본적인 구조는 “소스코드 어휘/문법 분석 – 문맥(타입) 체크 – 고유 동작“이며, 인터프리터는 명령의 수행, 컴파일러는 (다른 언어로 쓰인) 코드를 생성한다는 점에서 차이를 보인다.
  • #16 중간언어를 사용하기 때문에 소스코드의 하드웨어 의존성을 없앨 수 있다.
  • #17 Program을 실행하는 대신 Native Code 를 생성하면 Compiler가 된다. Intermediate code에 비해 프로그램 구조 유지 및 최적화된 경우에는 더 간단한 표현이 가능하기 때문에 일반적으로 Intermediate code보다 선호됨 (컴파일러 내부동작 관점?) 최악의 경우에는 트리 노드에서 활용도에 비해 찾아다니는 비용이 더 커져서 오버헤드가 더 커지기도 한다.
  • #19 실행 중에 일부 코드를 Native Code로 변환, 최적화된 Intermediate code를 생성하는 기법
  • #20 해당 언어의 컴파일러가 없을 때 Self-interpreter를 만들어서 명령어 수행을 가능하게 한다.
  • #28 쉘=명령줄, CLI
  • #29 참 쉽죠?
  • #31 입력의 마지막이 newline(\n)이다.
  • #32 동작 절차 읽기-처리-실행-표시 + 히스토리 저장