제 4 장 자바 소개

Download Report

Transcript 제 4 장 자바 소개

제 4장 프로그래밍 언어의 구문과 구현 기법
4.1 언어 구문
4.2 프로그래밍 언어 구현 기법
가상 컴퓨터
컴퓨터를 가상의 고급 언어 컴퓨터로 간주
가상의
Ada
컴퓨터
가상의
Assembly
언어
컴퓨터
Ada
번역기
운영 체제
명령어
번역기
가상의
C++
컴퓨터
C++
번역기
운영 체제
어셈블러
Cobol
번역기
computer
hardware
Lisp
인터프리터
가상의
Lisp 컴퓨터
Power
Builder
인터프리터
가상의
Power
Builder
컴퓨터
.......
가상의
Cobol
컴퓨터
구문 정의
4.1 언어 구문
4.1.1 프로그래밍 언어의 어휘 구조
프로그래밍 언어의 기본 문자 집합
알파벳 (A∼Z) 26개
아라비아 (0∼9) 10개
특수 문자 (+, -, ,, …)
문자 코드 체계
EBCDIC (Extended Binary Coded Decimal Interchange Code)
ASCII (American Standard Code for Information Interchange)
유니코드
구문 정의
정합순서 (collecting sequence)
문자 또는 문자열에 대한 일반적 순서
비트 조합 순서에 영향 받음
예) 0 < 1 < 2 < 3 < 4 < 5 < 6 < 7 < 8 < 9
A < B < C < ... < X < Y < Z
문자 -> 단어 -> 언어
예약어 (reserved word, key word)
프로그램 판독성 증가
기호 테이블 빠른 탐색
많은 예약어 기억하기 어려움
중복여지가 프로그램 혼돈 우려
형식언어의 문법(Formal Grammar)
G = ( VN, VT, P, S )
– VN : non-terminal Symbol의 유한집합
– VT : terminal Symbol의 유한집합
• VN VT =  V(Vocabulary) = VN  VT
– P : 생성규칙의 유한집합
•    (유도)
 V+   V*
– S : start Symbol  VN
예제
VN = {<sentence>,<subject>,<verb>,<object>,<noun>,<article>}
VT = {The, Boy, Girl, Loves, .}
S = <sentence>
P : 1. <sentence>  <subject><verb><object>.
2. <subject>  <article><noun>
3. <object>  <article><noun>
Left most derivation
4. <verb>  Loves
Top-down방식
5. <article>  The
6. <noun>  Boy | Girl
derivation(replacement:유도)
<sentence> => <subject><verb><object>.
=> <article><noun><verb><object>.
=> The <noun><verb><object>.
=> The Boy <verb><object>.
Sentential Form
=> The Boy Loves <object>.
=> The Boy Loves <article><noun>.
=> The Boy Loves The <noun>.
Sentence
=> The Boy Loves The Girl.
Right most derivation
Bottom-up방식
형식 언어의 문법의 분류
Chomsky 4 type Grammar
– 생성 규칙의 형태에 따라 구분
0) Type 0(Unrestricted Grammar)
• 생성 규칙에 어떤 제한도 두지 않는다. (위축형 문법)
예제 ) bc  b
1) Type 1(Context-sensitive Grammar :csg)
• 오른쪽이 왼쪽보다 같거나 긴 생성규칙
• || ≤ ||
예제)
P : A  abc
Bb  BC
A  aABc
CB  cc
bc  c (X)
2) Type 2 (Context-free Grammar:cfg)
– 왼쪽은 하나의 nonterminal symbol만 가능
–
  
예제 )
 : nonterminal

V*
L(G2) = {anban | n 1}
G2 = ({S, C}, {a, b}, P, S),
P : S  aCa
C  aCa
Cb
3) Type 3(Regular Grammar : rg : 정규문법)
– 왼쪽에 하나의 nonterminal symbol이 오고, 오른쪽도 최대한
하나의 nonteminal symbol이거나 terminal symbol로 구성
*
– A  tB A  t t  Vt A,B  VN (right linear regular grammar)
– A  Bt
예제 )
At
*
t  Vt A,B  VN
L(G3) = {anbam | n, m 1}
G3 =({S,B,C}, {a,b}, P, S),
P : S  aS
S  aB
B  bC
C  aC
(left linear regular grammar)
Ca
Regular 언어
Context-free 언어
Context-sensitive 언어
Unrestricted 언어
 언어의 포함관계
Grammar
Type 0(unresticted)
Type 1(context-sensitive)
Type 2(context-free)
Type 3(regular)
Language
Recusively enumerable
set
Context-sentive
language
Context-free language
Regular language
Recongnizer
Turing machine
Linear bounded
automata
Pushdown automata
Finite automata
 문법형태에 따른 언어와 인식기
구문 정의
4.1.2 문맥 자유 문법과 BNF
BNF (Backus-Naur Form) : context free grammar
구문 (Syntax) 형식 정의 보편적 방법
언어의 생성 규칙 정의
메타 기호
::=
정의하다
<>
nonterminal : 다시 정의될 대상
|
택일
구문 정의
식별자 정의의 BNF 표기
<identifier> ::= <letter> | <identifier><letter> |
<identifier><digit>
<letter> ::= A | B | C | … | X | Y | Z
<digit> ::= 0 | 1 | 2 | … | 8 | 9
구문 정의
예) AB1C
<identifier>
::=
::=
::=
::=
::=
::=
::=
::=
<identifier><letter>
<identifier><digit><letter>
<identifier><letter><digit><letter>
<letter><letter><digit><letter>
A <letter><digit><letter>
AB <digit><letter>
AB1 <letter>
AB1C
구문 정의
EBNF (Extended Backus-Naur Form) 표기법
BNF 확장하여 읽기 쉽고 간단한 표기법
BNF에 추가된 메타 기호
{} : 0번 이상 반복 ( { }07 )
[] : 0번 또는 1번 선택
() : 택일 연산자
‘ ‘ : terminal 표시
구문 정의
EBNF의 예
식별자
<id-name> ::= <alphabet> { <alphanumeric> }07
<alphanumeric> ::= <alphabet> | <digit>
<alphabet> ::= A | B | C | … | Z
<digit> ::= 0 | 1 | 2 | … | 9
If - then - else
<if-statement> ::= if <condition> then
<statement> [else<statement>]
구문 정의
사칙 연산
BNF
<expression> ::= <expression> + <expression> |
<expression> - <expression> |
<expression> * <expression> |
<expression> / <expression>
EBNF
<expression> ::= <expression>(+|-|*|/)<expression>
구문 정의
메타 기호가 terminal 기호 일 때
<BNF-rule> ::= <left-part> ‘::=‘ <right-part>
<right-part> ::= <right-part-element>
{ ‘|’ <right-part-element> }
구문 정의
Subpascal 시작부에 대한 EBNF
<subpascal> ::=program <ident>;<block> .
<block> ::=[<const_dcl>][<var_dcl>]{<proc_dcl>}
<compound-st>
<const_dcl> ::=const <ident> = <number>
{;<ident> = <number> };
<var_dcl> ::=var <ident_list> : <type>
{; <ident_list> : <type> };
<ident_list> ::=<ident> {,<ident>}
<proc_dcl> ::=procedure <ident>['('<formal_param>')'];
<block>;
<compound-st> ::=begin <statement> {;<statement>} end
구문 정의
4.1.3 구문 도표
구문 도표 (syntax diagram)
구문 도표는 그 형태가 순서도와 유사
구문 구문 도표는 EBNF 와 일대일 대응
다시 정의될 대상은 네모칸으로 terminal 기호는
원이나 타원형으로 표시
이들 사이는 지시선으로 연결
구문 정의
구문 도표 그리는 방법
① terminal x
X
② nonterminal B
B
구문 정의
③ A ::= X1X2 ...Xn
ⓐ Xi가 nonterminal인 경우
X1
A
X2
...
Xn
...
xn
ⓑ Xi가 terminal인 경우
x2
x1
A
④ A ::= α1|α2|...|αn
α1
A
α2
...
αn
구문 정의
⑤ EBNF A ::= {α}
A
α
⑥ EBNF A ::= [α]
A
α
⑦ EBNF A ::= (α1|α2)β
α1
β
A
α2
구문 정의
– 예제
EBNF
x
A
구문도표
(
A ::= x |’(‘ B’ )’
B ::= AC
C ::= {+A}
B
A
)
B
C
C
A
(조건)
VN = { A, B, C }
VT = { +, x, (, ) }
A
+
x
(
)
A
A
+
구문 정의
Subpascal 구문 도표
subpascal
program
ident
;
block
const
ident
=
number
block
·
;
var
:
ident
type
‘
;
;
ident
procedure
(
;
begin
formal-param
)
block
statement
;
end
구문 정의
4.1.4 파스 트리
파스 트리
원시 프로그램의 문법 검사 과정 중 생성 트리
구문 검사하는 검증 트리
한 표현이 BNF에 의해 작성될 수 있는지 여부
구문 정의
예) TEST1
<identifier> ::=<letter>|
<identifier><letter> |
<identifier><digit>
<letter> ::=A | B | C | ... | X | Y | Z
<digit> ::=0 | 1 | 2 | ... | 8 | 9
<identifier>
<digit>
<identifier>
<identifier>
<identifier>
<identifier>
<letter>
<letter>
<letter>
<letter>
T
E
S
T
1
<exp> ::= <exp> - <exp> | <exp> * <exp> | (<exp>) | <number>
<number> ::= <number> <digit> | <digit>
<digit> ::= 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9
<exp>
<exp>
-
<exp>
<number>
<exp>
<digit>
<number>
<number>
<digit>
<digit>
3
2
*
<exp>
5
<exp>
<exp>
<number>
<digit>
3
-
<exp>
<exp>
*
-
<exp>
<number> <number>
<digit>
2
<digit>
*
3
2
5
5
이 파스트리에서 불필요하게 표현되어 있는 비단말 기호들
을 없애면 추상구문(AST) 트리 혹은 구문트리(syntax tree)가
된다.
4.1.5 모호성, 결합성 및 우선순위
예) B33 생성 유도 과정
<identifier>
<identifier><digit>
<identifier> 3
<identifier> <digit> 3
<identifier> 3 3
<letter> 3 3
B33
<identifier>
<identifier><digit>
<identifier><digit><digit>
<letter> <digit> <digit>
B <digit> <digit>
B 3 <digit>
B33
예) B33 의 파스트리
<identifier>
<digit>
<identifier>
<identifier>
<digit>
3
<letter>
B
3
예) 3 – 2 * 5 수식의 생성 유도 과정
<exp>
<exp> - <exp>
<exp> - <exp> * <exp>
(두번째 <exp> 이 <exp> * <exp> 으로 대치)
<number> - <exp> * <exp>
….
3–2*5
<exp>
<exp> * <exp>
<exp> - <exp> * <exp>
(첫번째 <exp>이 <exp> - <exp>으로 대치 )
<number> - <exp> * <exp>
….
3–2*5
예) 두가지 서로 다른 파스트리
<exp>
<exp>
3
<exp>
-
<exp>
2
*
<exp>
5
3
-
*
2
<exp>
5
같은 문법에서 같은 스트림에 대하여 두가지 이상의
서로 다른 파스트리가 발생하면 이러한 문법은 모호
(ambiguous)하다고 한다.
예) Unambiguous 문법(분명한 문법)
수식 우선 순위의 문제 해결
<exp> ::= <exp> - <term> | <term>
<term> ::= <term> * <factor> | <factor>
<factor> ::= (<exp>) | <number>
<number> ::= <number> <digit> | <digit>
<digit> ::= 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9
구문 정의
4.1.6 구문과 프로그램 신뢰성
구문
프로그램의 신뢰성 증대 시키는데 큰 영향
구문 정의
예)
FORTRAN
DO 10 I = 2.6
A(I) = B + C(I)
10 CONTINUE
2.6의 오류(. 대신 , 사용해야함)
DO10I에 2.6 배정으로 인식
PL/I
A=B=C
다중배정문의 의미(A와 B에 C값 저장)
(B = C)의 결과를 A에 저장하는 문장으로 인식
구문 정의
If cond1 then if cond2 then s1 else s2
①
If cond1 then (if cond2 then s1 else s2)
②
If cond1 then (if cond2 then s1) else s2
Dangling (현수) else 문제
중첩된 if 문에서 else는 어떤 if의 else 인가?
if <cond> then <s>
if <cond> then <s> else <s>
구문 정의
<s> ::= if <cond> then <s> |
if <cond> then <s> else <s> | s1 | s2
<cond> ::= cond1 | cond2
①
②
<s>
If <cond> then <s> else <s>
if <cond> then <s>
cond1
If <cond> then <s> else <s>
cond2
<s>
s1
s2
cond1 if <cond> then <s>
cond2
s1
s2
구문 정의
언어별 현수 else 문제의 해결 방안
Algol 60 :
- ①의 경우
if cond1 then begin if cond2 then s1 else s2 end
- ②의 경우
if cond1 then begin if cond2 s1 end else s2
Algol 68 :
- ①의 경우
if cond1 then if cond2 then s1 else s2 fi fi
- ②의 경우
if cond1 then if cond2 s1 fi else s2 fi
PL/I :
- ② 의 경우
IF cond1 THEN IF cond2 THEN s1; ELSE s2;
또는
IF cond1 THEN IF cond2 THEN s1; ELSE; ELSE s2;
Pascal :
- ② 의 경우
if cond1 then begin if cond2 then s1 then else s2
또는
if cond1 then if cond2 then s1 else else s2
※ PL/I 과 파스칼에서 일반적으로 사용된 경우 ①의 경우로 해석됨.
구문 정의
Sample List (1-1) *PASCAL*
Program Compare(input, Output);
Var
x, y, z : integer;
Begin
z := 7;
writeln(‘Type the each variables x, y, z ‘);
write (‘ x= ‘);
readln (x);
write (‘ y= ‘);
readln (y);
if x > 0 then
if y > 5 then
z := x + y
else
z := x + y;
writeln(‘x = ‘, x, ‘ y = ‘, y, ‘ z= ‘, z)
end.
구문 정의
Sample List (1-2) *C*
#include <stdio.h>
void main()
{
int x, y, z = 7;
printf(“ Type the each variables x, y, z\n”);
printf(“x = “);
scanf(“%d”, &x);
printf(“y =“);
scanf(“%d”, &y);
if (x > 0)
if (y > 5)
z = x + y;
else
z = 0;
printf(“\n x = %d, y = %d, z = %d\n”, x, y, z);
}
Sample List (1-3) *JAVA*
import java.io.*;
public class A {
public static void main(String[] args) throws IOException {
String strx;
String stry;
int x,y,z=7;
BufferedReader in = new BufferedReader(
new InputStreamReader(System.in));
System.out.println("Type the each variables x, y");
System.out.print("x = ");
strx = in.readLine();
x = Integer.parseInt(strx);j
// x = new Integer(strx);
// Java 5.0 이상
System.out.print("y = ");
stry = in.readLine();
y = Integer.parseInt(stry);
if (x > 0)
if (y > 5)
z = x + y;
else
z = 0;
System.out.println("x = "+ x + ", y = " + y+", z = "+z);
}
}
Sample List (1-4) *JAVA*
import java.io.*;
public class B {
public static void main(String[] args) throws IOException {
int x,y,z=7;
System.out.println("Type the each variables x, y");
x = System.in.read() - '0';
y = System.in.read() - '0';
if (x > 0)
if (y > 5)
z = x + y;
else
z = 0;
System.out.println("x = "+ x + ", y = " + y+", z = "+z);
}
}
구문 정의
Sample List (2-1) *PASCAL*
Program Compare(input, Output);
Var
x, y, z : integer;
Begin
writeln(‘Type the each variables x, y, z ‘);
write (‘ x= ‘);
readln (x);
write (‘ y= ‘);
readln (y);
if x > 0 then
if y > 5 then
z := x + y
else
else
z := 0;
writeln(‘x = ‘, x, ‘ y = ‘, y, ‘ z= ‘, z)
end.
구문 정의
Sample List (2-2) *C*
#include <stdio.h>
void main()
{
int x, y, z;
z = 7;
printf(“ Type the each variables x, y, z\n”);
printf(“x = “);
scanf(“%d”, &x);
printf(“y =“);
scanf(“%d”, &y);
if (x > 0) {
if (y > 5)
z = x + y;
else
z = 0; }
printf(“\n x = %d, y = %d, z = %d\n”, x, y, z);
}
Sample List (2-3) *JAVA*
import java.io.*;
public class A {
public static void main(String[] args) throws IOException {
String strx;
String stry;
int x,y,z=7;
BufferedReader in = new BufferedReader(
new InputStreamReader(System.in));
System.out.println("Type the each variables x, y");
System.out.print("x = ");
strx = in.readLine();
x = Integer.parseInt(strx);
// x = new Integer(strx);
// Java 5.0 이상
System.out.print("y = ");
stry = in.readLine();
y = Integer.parseInt(stry);
if (x > 0) {
if (y > 5)
z = x + y;
else
z = 0;
}
System.out.println("x = "+ x + ", y = " + y+", z = "+z);
}
}
Sample List (2-4) *JAVA*
import java.io.*;
public class B {
public static void main(String[] args) throws IOException {
int x,y,z=7;
System.out.println("Type the each variables x, y");
x = System.in.read() - '0';
y = System.in.read() - '0';
if (x > 0) {
if (y > 5)
z = x + y;
else
z = 0;
}
System.out.println("x = "+ x + ", y = " + y+", z = "+z);
}
}
구문 정의
Sample List (3-1) *PASCAL*
Program Compare(input, Output);
Var
x, y, z : integer;
Begin
z := 7;
writeln(‘Type the each variables x, y, z ‘);
write (‘ x= ‘);
readln (x);
write (‘ y= ‘);
readln (y);
if x > 0 then
begin
if y > 5 then
z := x + y
end
else
z := 0;
writeln(‘x = ‘, x, ‘ y = ‘, y, ‘ z= ‘, z)
end.
구문 정의
Sample List (3-2) *C*
#include <stdio.h>
void main()
{
int x, y, z;
z = 7;
printf(“ Type the each variables x, y, z\n”);
printf(“x = “);
scanf(“%d”, &x);
printf(“y =“);
scanf(“%d”, &y);
if (x > 0) {
if (y > 5)
z = x + y;
}
else
z = 0;
printf(“\n x = %d, y = %d, z = %d\n”, x, y, z);
}
Sample List (3-3) *JAVA*
import java.io.*;
public class A {
public static void main(String[] args) throws IOException {
String strx;
String stry;
int x,y,z=7;
BufferedReader in = new BufferedReader(
new InputStreamReader(System.in));
System.out.println("Type the each variables x, y");
System.out.print("x = ");
strx = in.readLine();
x = Integer.parseInt(strx);
// x = new Integer(strx);
// Java 5.0 이상
System.out.print("y = ");
stry = in.readLine();
y = Integer.parseInt(stry);
if (x > 0) {
if (y > 5)
z = x + y;
}
else
z = 0;
System.out.println("x = "+ x + ", y = " + y+", z = "+z);
}
}
Sample List (3-3-1) *JAVA*
import java.util.*;
public class ScanJava {
public static void main(String[] args){
int x,y;
int z = 0;
Scanner scan = new Scanner(System.in);
System.out.println("Type the each variables x,y");
System.out.print("x= " );
x = scan.nextInt();
System.out.print("y = " );
y = scan.nextInt();
if(x > 0)
if(y>5)
z = x + y;
else
z = 0;
System.out.println("x = " + x + ", y = " + y + ", z = " + z);
}
}
Sample List (3-4) *JAVA*
import java.io.*;
public class B {
public static void main(String[] args) throws IOException {
int x,y,z=7;
System.out.println("Type the each variables x, y");
x = System.in.read() - '0';
y = System.in.read() - '0';
if (x > 0) {
if (y > 5)
z = x + y;
}
else
z = 0;
System.out.println("x = "+ x + ", y = " + y+", z = "+z);
}
}
프로그래밍 언어 설계
4.2 프로그래밍 언어 구현 기법
구현 방법
번역 기법 (Translation)
어떤 원시(Source) 언어를 입력으로 목적 언어로
된 기능이 동등한 프로그램을 출력해 주는 언어
처리기
인터프리터 기법(Interpretation)
고급 언어로 된 프로그램을 읽어 각 문장을 디코딩
하고 실행시키는 언어 처리기
프로그래밍 언어 설계
번역 기법 (Translation)
source
(원시 언어)
target
(목적 언어)
translator
원시
프로그램
목적
프로그램
고급
언어
컴파일러
목적
모듈
고급
언어
컴파일러
목적
모듈
고급
언어
컴파일러
목적
모듈
입력 자료
.
.
.
어셈블리
언어
.
.
.
.
.
.
어셈블러
LINKER
로드
모듈
로더
기계어
실행 결과
목적
모듈
프로그래밍 언어 설계
번역기의 종류
Preprocessor
원시 언어 : 고급 언어
목적 언어 : 고급 언어
Compiler
원시 언어 : 고급 언어
목적 언어 : 저급 언어(어셈블리, 준 기계어)
Assembler
원시 언어 : 어셈블리 언어
목적 언어 : 준기계어 언어
프로그래밍 언어 설계
Linkage Editor
원시 언어 : 여러 개의 프로그램
목적 언어 : 로드 모듈 생성
(실행 가능한 하나의 기계어)
Loader
원시 언어 : 로드 모듈
목적 언어 : 실행 가능한 기계어
(excutable code)
프로그래밍 언어 설계
인터프리터 기법(1)
입력자료
고급 언어로
작성된
원시 프로그램
인터프리터
실행 결과
프로그래밍 언어 설계
인터프리터 기법(2)
원시
프로그램
적당한 번역과정
중간 형태 코드
인터프리터
실행 결과
입력자료
Java
Java
바이트코드
프로그램
컴파일러(javac)
Java 가상기계의
바이트
코드
바이트코드 인터프리터
Java 가상 기계가 작동하고 있는 실제 기계
< Java 바이트 코드 컴파일 >
출력
결과
프로그래밍 언어 설계
번역기 종류와 인터프리터
원시 언어 ( 입력)
소프트웨어 프로그램
목적 언어 (출력)
고급 언어 프로그램
컴파일러
기계어, 준기계어
(목적 모듈)
어셈블러 프로그램
어셈블러
기계어, 준기계어
(목적 모듈)
목적모듈 (준기계어)
커 editor)
(linker,링
linkage
로드 모듈
로 더
(relocating loader)
고급 언어 프로그램
Preprocessor
원시 언어 (입력)
고급 언어 프로그램
소프트웨어 프로그램
(하드웨어 기능)
인터프리터
로드 모듈
실행 가능 기계어
고급 언어 프로그램
출
력
프로그램이
실행된 결과
프로그래밍 언어 설계
번역 기법과 인터프리터 기법 비교
번역기
입력 프로그램과 동일한 의미의 목적 언어
프로그램 생성
장점 : 실행 시간 효율성 (efficiency)
단점 : 큰 기억 장치 요구
컴파일러 언어
FORTRAN, ALGOL, PL/I, PASCAL, COBOL
C, Ada
프로그래밍 언어 설계
인터프리터
중간 언어를 생성 후 중간 언어로 작성된
프로그램을 번역, 실행
장점 : 사용자의 적응성 (flexibility)
단점 : 실행 시 많은 디코딩 시간 요구
인터프리터 언어
LISP, SNOBOL, APL, PROLOG